Skip to content

Commit 5de24cd

Browse files
committed
streamline calculate_sum_and_product to use a single loop for efficiency
1 parent 2f6d1b9 commit 5de24cd

1 file changed

Lines changed: 25 additions & 20 deletions

File tree

‎Sprint-1/Python/calculate_sum_and_product/calculate_sum_and_product.py‎

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,32 @@ def calculate_sum_and_product(input_numbers: List[int]) -> Dict[str, int]:
55
"""
66
Calculate the sum and product of integers in a list.
77
8-
Note: the sum is every number added together
9-
and the product is every number multiplied together
10-
so for example: [2, 3, 5] would return
11-
{
12-
"sum": 10, // 2 + 3 + 5
13-
"product": 30 // 2 * 3 * 5
14-
}
15-
Time Complexity:
16-
Space Complexity:
17-
Optimal time complexity:
18-
"""
19-
# Edge case: empty list
20-
if not input_numbers:
21-
return {"sum": 0, "product": 1}
8+
Time Complexity: O(n)
9+
Space Complexity: O(1)
10+
Optimal Time Complexity: O(n)
11+
12+
Refactor:
13+
The original implementation iterated through the list twice:
14+
once to calculate the sum and once to calculate the product.
15+
This refactor combines both calculations into a single loop,
16+
reducing the number of iterations while maintaining O(n)
17+
time complexity.
2218
23-
sum = 0
24-
for current_number in input_numbers:
25-
sum += current_number
19+
Args:
20+
input_numbers: List of integers.
2621
22+
Returns:
23+
Dictionary containing the sum and product.
24+
"""
25+
26+
total_sum = 0
2727
product = 1
28-
for current_number in input_numbers:
29-
product *= current_number
3028

31-
return {"sum": sum, "product": product}
29+
for number in input_numbers:
30+
total_sum += number
31+
product *= number
32+
33+
return {
34+
"sum": total_sum,
35+
"product": product,
36+
}

0 commit comments

Comments
 (0)