Skip to content

Commit 13822d7

Browse files
committed
calculate sum and products
1 parent 1c0d205 commit 13822d7

1 file changed

Lines changed: 14 additions & 10 deletions

File tree

Sprint-1/Python/calculate_sum_and_product/calculate_sum_and_product.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,24 @@ def calculate_sum_and_product(input_numbers: List[int]) -> Dict[str, int]:
1212
"sum": 10, // 2 + 3 + 5
1313
"product": 30 // 2 * 3 * 5
1414
}
15-
Time Complexity:
16-
Space Complexity:
17-
Optimal time complexity:
15+
Time Complexity: O(n)
16+
Space Complexity: O(1)
17+
Optimal time complexity: O(n)
18+
Explanation: The function loops through the list of input numbers twice, once to calculate the
19+
sum and once to calculate the product. The results in O(n n) = O(n) time. It uses only
20+
21+
Refactor: We can calculate both the sum and product in a single loop,
22+
which reduces the time complexity to O(n).
1823
"""
1924
# Edge case: empty list
2025
if not input_numbers:
2126
return {"sum": 0, "product": 1}
2227

23-
sum = 0
24-
for current_number in input_numbers:
25-
sum += current_number
28+
total_sum = 0
29+
total_product = 1
2630

27-
product = 1
28-
for current_number in input_numbers:
29-
product *= current_number
31+
for num in input_numbers:
32+
total_sum += num
33+
total_product *= num
3034

31-
return {"sum": sum, "product": product}
35+
return {"sum": total_sum, "product": total_product}

0 commit comments

Comments
 (0)