Reputation: 11
Ok so this is the code I'm working with that keeps giving me this error:
def median(lst):
slst = lst.sort()
if len(slst) == 1:
median = lst[0]
else:
index = len(slst) - 1
if len(slst) % 2 != 0:
median_index = index / 2
median = slst[median_index]
else:
upper_val_index = len(slst) / 2
lower_val_index = upper_val_index + 1
upper_val = slst[upper_val_index]
lower_val = slst[lower_val_index]
average = (lower_val + upper_val) / 2.0
median = average
return median
I already tried using the sorted() function on the list but that does not work either. I'm just starting out with python so not so complicated answers are appreciated :) thanks!
Upvotes: 1
Views: 1812
Reputation: 22954
Actually the .sort() method does the sorting on the list itself by changing the order of the elements in the list and it doesnot returns anything, So you have 2 choices:
"""
1. Either use the .sort() method as lst.sort() # This will change the original list.
2. Use the sorted() method which returns a new list. and you can easily assign it to new variable.
"""
def median(lst):
slst = sorted(lst)
if len(slst) == 1:
median = lst[0]
else:
index = len(slst) - 1
if len(slst) % 2 != 0:
median_index = index / 2
median = slst[median_index]
else:
upper_val_index = len(slst) / 2
lower_val_index = upper_val_index + 1
upper_val = slst[upper_val_index]
lower_val = slst[lower_val_index]
average = (lower_val + upper_val) / 2.0
median = average
return median
Here is the slight modification of the code for making it to work desirably, Kindly study the differences and try to learn from the mistakes, There are sure some more good ways to achieve the same but this required the minimal change .
def median(lst):
slst = sorted(lst)
if len(slst) == 1:
median = lst[0]
else:
index = len(slst)
if len(slst) % 2 != 0:
median_index = index / 2
median = slst[median_index]
else:
upper_val_index = len(slst) / 2
lower_val_index = upper_val_index - 1
upper_val = slst[upper_val_index]
lower_val = slst[lower_val_index]
average = (lower_val + upper_val) / 2.0
median = average
return median
print median([4,5,5,4])
>>> 4.5
print median([4,5,5,5,4])
>>> 5
Upvotes: 1
Reputation: 599490
Methods that modify existing lists, like sort
, do not return anything. So your code sets slst
to None.
Instead, just call the method without assigning:
def median(lst):
lst.sort()
if len(slst) == 1:
median = lst[0]
Alternatively, you can use lst = sorted(lst)
, which does return a new list, but that is unnecessary.
Upvotes: 2