0
Follow
0
View

List Indices must be integer or slices, not float

wurb1975 注册会员
2023-01-25 19:58

/ 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

About the Author

Question Info

Publish Time
2023-01-25 19:58
Update Time
2023-01-25 19:58