4 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
問(wèn)題:
您正在訪(fǎng)問(wèn)
myEvenList
andmyOddList
insidemedianCalculator
,但您不應(yīng)該這樣做。medianCalculator
應(yīng)與任何外部變量分離。參數(shù)
myEvenList
隱藏myEvenList
全局變量您決定運(yùn)行偶數(shù)還是奇數(shù)算法取決于
n
,它是根據(jù) 計(jì)算的myOddList
,因此它始終只運(yùn)行兩側(cè)之一。不要調(diào)用
sort()
參數(shù),因?yàn)樗鼤?huì)修改底層列表。先復(fù)印一份。
解決方案:
讓你的
medianCalculator
函數(shù)沒(méi)有副作用。這意味著,它不應(yīng)該訪(fǎng)問(wèn)其自身函數(shù)之外的任何變量,而只能對(duì)其輸入?yún)?shù)進(jìn)行操作。medianCalculator
如果您想獲得多個(gè)答案,請(qǐng)多次致電。使用不同的參數(shù)讓它在不同的輸入上運(yùn)行。
代碼:
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貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
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貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
你得到 3 因?yàn)槟愫雎粤薽yEvenList
n = len(myOddList)
if n % 2 != 0: # always true
answerOdd = myOddList[int(n/2)]
return answerOdd # return 3
不要在函數(shù)中使用兩個(gè)列表,而只使用給定的參數(shù)

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
首先你創(chuàng)建一個(gè) def,所以不要在那里創(chuàng)建你的列表,其次你應(yīng)該定義一個(gè) def 參數(shù),因?yàn)槟闵院笙胍褂谩?/p>
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)
添加回答
舉報(bào)