15/15 'float' object is not iterable


#1

Here is my code:

def median(x):
  sorted(x)
  
  
  if len(x) % 2 != 0:
    y = x[0:len(x) / 2 + 1]
    z = y[len(y) - 1 : len(y)]
    return sum(z)
  else:
    a = x[0:len(x) / 2 + 1]
    b = a[len(a) - 1 : len(a)]
    b = sum(b)
    c = a[len(a) - 2 : len(a) - 1]
    c = sum(c)
    d = (b + c) / 2.0
    return sum(d)

I get error message:

median([4, 5, 5, 4]) resulted in an error: ‘float’ object is not iterable

I have two questions: 1, how do I read this error message? what does is mean that something is not iterable? 2, I am using sum(b) to convert b from a list to an integer but this seems like a bad way. Is there a better way to do this?

Thanks!


#3

Returns None, for starters. Be sure to assign this, even to itself, though better a local variable…

x = sorted(x)    # okay

s = sorted(x)    # better

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.