Exercise 90 *
Given a list of integers
L = [n1, n2, n3, ..., np]
, write an algorithm in python which returns the list:
L_sum = [n1, n1 + n2, n1 + n2 + n3, .. ., n1 + n2 + n3 + ... + np]
Solution
# function which calculates the sum of the list elements
def sumList (L):
# initialization of the sum of the list elements
s = 0
for x in L:
s = s + x
return s
# function which determines the list L_sum
def sum_list (L):
# initializationh of the list L_sum
L_sum = []
for i in range (0, len (L)):
L_sum.append (sumList (L [0: i+1]))
return L_sum
# Example
L = [3, 2, 5, 1, 0, 7]
print ("L_sum =", sum_list (L))
Younes Derfoufi
my-courses.net
my-courses.net