4 回答
TA贡献1797条经验 获得超6个赞
问题:
您正在访问
myEvenList
andmyOddList
insidemedianCalculator
,但您不应该这样做。medianCalculator
应与任何外部变量分离。参数
myEvenList
隐藏myEvenList
全局变量您决定运行偶数还是奇数算法取决于
n
,它是根据 计算的myOddList
,因此它始终只运行两侧之一。不要调用
sort()
参数,因为它会修改底层列表。先复印一份。
解决方案:
让你的
medianCalculator
函数没有副作用。这意味着,它不应该访问其自身函数之外的任何变量,而只能对其输入参数进行操作。medianCalculator
如果您想获得多个答案,请多次致电。使用不同的参数让它在不同的输入上运行。
代码:
myOddList = [1, 2, 3, 4, 5]
myEvenList = [1, 2, 3, 4, 5, 6]
def medianCalculator(myList):
myList = myList.copy()
myList.sort()
n = len(myList)
if n % 2 != 0:
answerOdd = myList[int(n/2)]
return answerOdd
else:
one = myList [(n-1) // 2]
two = myList [(n+1) // 2]
answerEven = (one + two) / 2
return answerEven
medianForEvenList = medianCalculator(myEvenList)
print(medianForEvenList)
medianForOddList = medianCalculator(myOddList)
print(medianForOddList)
TA贡献1831条经验 获得超4个赞
myOddList = [1, 2, 3, 4, 5]
myEvenList = [1, 2, 3, 4, 5, 6]
def median(lst):
lst = sorted(lst)
lst_length = len(lst)
midpoint = lst_length/2
if lst_length % 2 != 0:
return lst[int(midpoint-0.5)]
else:
return (lst[int(midpoint-0.5)] + lst[int(midpoint+0.5)])/2
print(median(myOddList))
# 3
print(median(myEvenList))
# 3.5
TA贡献1859条经验 获得超6个赞
你得到 3 因为你忽略了myEvenList
n = len(myOddList)
if n % 2 != 0: # always true
answerOdd = myOddList[int(n/2)]
return answerOdd # return 3
不要在函数中使用两个列表,而只使用给定的参数
TA贡献2041条经验 获得超4个赞
首先你创建一个 def,所以不要在那里创建你的列表,其次你应该定义一个 def 参数,因为你稍后想要使用。
def median_cal (my_list) :
my_list.sort()
n = len(my_list)
if n % 2 != 0 :
x = int(n/2)
answer = my_list[x]
print (answer)
else :
x = int(n/2) - 1
y = int(n/2)
answer = my_list[x] + my_list[y]
print (answer/2)
a = [1,2,3]
b = [1,2,3,4]
median_cal(a)
median_cal(b)
添加回答
举报