0

当我在 PyScripter 上运行我的程序时,我得到了4.5. 但是在 Ideone 上运行与此处或在codeacademy上相同的代码会返回4。知道为什么会有不同的结果吗?谢谢。

#Create a function that returns the median of a list of numbers
def median(list_of_numbers):

#Make a copy of list_of_numbers and sort the new list
    lst = list_of_numbers
    lst = sorted(lst)

#Get the length of list and use it to index through the list
    lst_length = len(lst)
    index = int(lst_length/2)

#If length if even, average the two middle numbers
    if lst_length%2==0:
        a=  lst[index-1]
        b = lst[index]
        result = (a+b)/2

#If length is odd, return the middle number
    else:
        result = lst[index]
    return result

print (median([4, 5, 5, 4]))

我的 PyScripter 版本:* Python 3.3.5(v3.3.5:62cf4e77f785,2014 年 3 月 9 日,10:37:12)[MSC v.1600 32 位(英特尔)] 在 win32 上。*

4

2 回答 2

1

对于 Python 2.x,您将需要替换两个出现的2by2.以强制执行浮点除法。

您与 ideone 的链接是 Python 2.x,显然您的 codeacademy 解释器也是如此。

于 2014-06-27T03:01:30.550 回答
0
import statistics as s

def mid(data):
    return(int(s.median(data)))

middle = mid([3,4,6,3,12,6,45,32,78])
print(middle)

我会使用统计模块。如果您希望输出为整数或浮点数,只需将其强制转换(分别为 float() 或 int())。

于 2016-01-15T13:58:34.203 回答