0
[PYTHON3] I'm trying to Find the Cumulative Sum of a List where the ith Element is the Sum of the First i+1 Elements From The Or
#Find the Cumulative Sum of a List where the ith Element is the Sum of the First i+1 #Elements From The Original list i=1 x=[] while i != 0: i=int(input("Enter an element (enter 0 if u want to terminate the loop)")) if i == 0: break x.append(i) b=[sum(x[0:i+1] for i in range(0,len(x)))] print("Original List ",x) print("New List ",b) #this is my code but i'm ending up with an error msg. #TypeError: unsupported operand type(s) for +: 'int' and 'list'
4 Réponses
+ 6
Sousou is absolutely right. There is a paranthesis for sum() function on the wrong place.
+ 2
li =[1,3,5,5,14]
for i in range(1,len(li)):
if sum(li[:i]) == li[i]:
print(f"Element {i+1} = {li[i]} is the sum of {li[:i]}")
+ 1
#error in b (list comprehension) I think Maybe it should be:
b=[sum(x[0:i+1]) for i in range(0,len(x))]