Skip to content

Commit cc707ca

Browse files
committed
Optimized List Sum
1 parent bdedb32 commit cc707ca

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Optimized_List_Sum.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class ListFastSum:
2+
def __init__(self, nums):
3+
self.nums = nums
4+
self.sum_up_to = []
5+
6+
current_sum = 0
7+
for num in nums:
8+
current_sum += num
9+
self.sum_up_to.append(current_sum)
10+
11+
# Allows self.sum_up_to[-1] = 0
12+
self.sum_up_to.append(0)
13+
14+
def sum(self, start_idx, end_idx):
15+
return self.sum_up_to[end_idx - 1] - self.sum_up_to[start_idx - 1]
16+
17+
18+
print(ListFastSum([1, 2, 3, 4, 5, 6, 7]).sum(2, 5))
19+
# 12 because 3 + 4 + 5 = 12

0 commit comments

Comments
 (0)