+ 1
How to find the sum of the sum of numbers in a given list in Python 3?
There are N numbers in a list. We need to find the sum of the numbers from the start till the position of the list and then add that sum to the total. I have a code below which is slower than the expected solution. def fun(lst): total, till_now = 0, 0 for i in lst: till_now += i total += till_now return total Please help to make this code faster! Thank you so much!
6 Respuestas
+ 3
your codes does give result of 20 if i use list [1,2,3,4]. so i build a code that does the same:
def sum_(lst):
total = 0
for ind in range(len(lst)): #both for loops does work
#for ind, i in enumerate(lst):
total += sum(lst[:ind+1])
return total
print(sum_([1,2,3,4]))
+ 1
sum(list)
You want to add the numbers in a list?
+ 1
Did you mean to find the sum of all elements in a list?
def fun(lst):
total = 0
for i in range(0, len(lst)):
total += lst[i]
return total
+ 1
I meant to say that first I need to calculate the sum of the numbers from the start of the list till the position that I am at and then the total sum of those sums.
For example, if lst = [3, 4, 5]
first it should be lst[0] reading 3, lst[1] reading 3 + 4 = 7, lst[2] reading 3 + 4 + 5 = 12
so the expected answer is 3 + 7 + 12 = 22
+ 1
Thank you @Jay Matthews