-1

The code is supposed to create a new list m from an existing list x.

Every element m[i] is supposed to be the arithmetic mean of the i element in x, but I can't make it work in any way.

def mari(x):
   m = []
   i = 0
   for i in range(1,len(x)):
       m[i]=((sum(x[i])/i+1))
       i = i+1
   return m
x = [1, 2, 3, 4, 5]
print mari(x)

TypeError: 'int' object is not iterable

is what seems to prevent it from working.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
nsnro
  • 5
  • 2
  • Well, for one thing, `i = i+1` you don't modify the loop index like that. It automatically handles it. `sum(x[i])` You're trying to sum one number. – Morgan Thrapp Jan 14 '16 at 17:27

2 Answers2

0

The simplest and most efficient way is to keep separately the sum and the count of element of the input list. Then the arithmetic mean if just the current sum divided by the current count:

def mari(x):
    s = 0.0 # current sum
    cnt = 0 # current count
    m = [] # list to return
    for i in x:
        s += i
        cnt += 1
        m.append(s / cnt)
    return m
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

According to your code, You can try this:

def mari(x):
   m = []
   m.append(x[0])
   for i in range(1,len(x)):
           m.append((sum(x[0:i+1]))/(i+1))
   return m

x = [1, 2, 3, 4, 5]
print mari(x)
Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29