Exercise 92**
Write a python algorithm which transforms a list of integers
L = [n1, n2, n3, ...., np]
into a list whose elements are the averages of the partial sums:
[n1, average(n1, n2) , average(n1, n2, n3), ...., average(n1, n2, ..., np)]
Solution
# Function that calculates the average of a list of numbers
def average_list (L):
n = len (L)
# initialization of the sum of the list elements
sum = 0
for x in L:
sum = sum + x
return sum / n
# Function which determines the average list of the partial sums
def average_sum (L):
# initialization of the list of partial sums
l_average = []
for i in range (1, len (L)):
l_average.append (average_list (L [0: i]))
return l_average
# Example
L = [10, 14, 12, 10, 13, 15]
print (average_sum (L))
# The output is: [10.0, 12.0, 12.0, 11.5, 11.8]
Younes Derfoufi
my-courses.net
my-courses.net