0
我現在是一個Python新手,我通過完成http://www.codecademy.com課程來學習。該網站提供了一個在線評審系統,就像ACM一樣,可以檢查我的代碼是否正常工作。除了這個之外,它對我的其他代碼非常有用。有什麼不對我的python:float()參數必須是一個字符串或數字
我試圖將這段代碼複製到我的本地電腦與Python 2.6安裝,它的工作原理。
順便說一句,你可以建議一些Python語法書給像我這樣的初學者,我只是想知道這種語言有點內詳細...
因爲我不能在這裏張貼圖片我只是貼下面的代碼:
在我的Mac: :
[~ tk$]cat test8.py
def median(li):
if len(li) >= 2:
li_test = sorted(li)
if len(li_test)%2 == 0:
cd1 = len(li_test)/2-1
cd2 = cd1
re = (li_test[cd1] + li_test[cd2])/2.0
else:
cd = (len(li_test)+1)/2-1
re = li_test[cd]
else:
re = li
return re
print median([1,2,3])
[~ tk$]python test8.py
2
[~ tk$]
的網站:標題是:熟能生巧15/15:
def median(li):
if len(li) >= 2:
li_test = sorted(li)
if len(li_test)%2 == 0:
cd1 = len(li_test)/2-1
cd2 = cd1
re = (li_test[cd1] + li_test[cd2])/2.0
else:
cd = (len(li_test)+1)/2-1
re = li_test[cd]
else:
re = li
return re
Oops, try again. Your function crashed on [1] as input because your function throws a "float() argument must be a string or a number" error.
不,我不認爲我可以那樣做。這是一個網上裁判系統,所以我只能讓我的代碼滿足其標準。在[1]的長度爲1的情況下,顯然中位數是1,所以我只是返回了數字。我看不出錯誤。 –
你正在返回'list'' [1]'不是'int''1' – Jae
TK,來說明Jay的第二點 - '[1,3]'的中位數是多少? –