Когда я запускаю свою программу на 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, 9 марта 2014 г., 10:37:12) [MSC v.1600, 32 бита (Intel)] на win32. *
/
— деление пола, а в py3/
— деление с плавающей запятой. Попробуйте заменить2
на2.
. - person Hyperboreus   schedule 27.06.2014//
вместо/
? Например:int(lst_length//2)
- person OlympusMonds   schedule 27.06.2014result = (a+b)/2
на(a+b)/2.
. Изменение2
на2.
(или2.0
) приводит его к типу с плавающей запятой, всегда возвращая плавающее деление. В python2 по умолчанию/
означает целочисленное деление (если иa
, иb
являются целыми числами), в python 3 по умолчанию это деление с плавающей запятой. - person Imanol Luengo   schedule 15.01.2016