So I was creating a median calculator, and I came upon this error (the heading)
def median(x):
#finds the median of a column
if len(x) % 2 == 0:
y = len(x) / 2
medknot = x[y] x[y][-1]
med = medknot / 2
return med
elif len(x) % 2 == 1:
y = len(x)//2
med = x[y]
return med
l1 = [5, 6, 7, 8, 9, 6, 5, 5]
print(median(l1))
What is the error in my code?
CodePudding user response:
/
always returns a float, even if the result could be an integer.
>>> 1/1
1.0
Use:
y = len(x) // 2
Also, the next line doesn't make sense:
medknot = x[y] x[y][-1]
As the output of x[y]
should be a scalar. You probably want medknot = x[y] x[y-1]
Finally, the input list should be sorted to compute a correct median.
You can also simplify the code:
def median(x):
# sort x
x = sorted(x)
y = len(x) // 2
med = x[y]
if len(x) % 2 == 0:
med = (med x[y-1])/2
return med
print(median([1, 2, 3]))
# 2
print(median([1, 2, 3, 4]))
# 2.5
print(median([4, 1, 2, 3]))
# 2.5
CodePudding user response:
If you are working on the latest Python version 3.8 , you could try this standard statistics lib. It could also speed up in case you're dealing with a huge list of numbers.
from statistics import median
lst = [5, 6, 7, 8, 9, 6, 5, 5]
median_val = median(lst) # 6.0