2014-03-06 31 views
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
else: 
    re = li 

的錯誤發生,因爲如果li長度是1或0,那麼你就返回listli

>>> median([1]) 
[1] 
>>> median([0]) 
[0] 

也許你想

if len(li) >= 1: 
    ... 
else: 
    raise IndexError("No items in this list") 

在你的代碼中的另一個bug是如果有偶數個列表中的元素,你應該採取兩個中間元素的平均值。但在你的代碼中,

if len(li_test)%2 == 0: 
     cd1 = len(li_test)/2-1 
     cd2 = cd1 
     re = (li_test[cd1] + li_test[cd2])/2.0 

你拿兩個中間元素中的一個,並且將兩個相同的數字相加併除以二。它應該是

if len(li_test) % 2 == 0: 
     cd1 = len(li_test)/2 
     cd2 = cd1 - 1 
     re = (li_test[cd1] + li_test[cd2])/2.0 
+0

不,我不認爲我可以那樣做。這是一個網上裁判系統,所以我只能讓我的代碼滿足其標準。在[1]的長度爲1的情況下,顯然中位數是1,所以我只是返回了數字。我看不出錯誤。 –

+2

你正在返回'list'' [1]'不是'int''1' – Jae

+0

TK,來說明Jay的第二點 - '[1,3]'的中位數是多少? –

相關問題