2016-04-22 22 views
0

我想排序二進制列表,它應該像這樣工作:遞歸無法連接'int'和'NoneType' - 如何將'NoneType'更改爲'int'?

>>> blsort([1, 0, 1]) 
[0, 1, 1] 

所以我做了這個代碼:

def blsort(L): 
if L == []: 
    return [] 
elif L[0] == 0: 
    L.insert(0, 0) 
else: 
    L.append(1) 
    return L[0] + blsort(L[1:]) 

但我只得到這個錯誤:

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' 

所以不知何故,這段代碼返回一個NoneType,我不能連接intlist

我假設blsort(L[1:])NoneType類型。我能做些什麼來使它的類型爲int,所以我可以將它與其他int連接到list

+1

你是不是在這裏後,返回任何第二,如果條件'L.insert(0,0)' – AKS

+0

你爲什麼不使用'list.sort()' ? – Aurel

+0

我無法使用list.sort(),它是學校的一項任務,重點在於學習遞歸,因此不允許使用list.sort() – Manuel

回答

1

您還沒有經過第二if條件返回任何東西:

elif L[0] == 0: 
    L.insert(0, 0) 

所以,當這個語句執行的blsort回報是None導致錯誤。

return L[0] + blsort(L[1:]) 
+0

此外,終止條件會導致「TypeError」。 – letmutx

+0

是的,我也不確定整個程序。 – AKS

0

感謝您的回答,那確實是解決方案的一部分。解決方案的第二部分是寫[0](所以'0'作爲列表項)而不是L [0]。這裏

此代碼固定它:

def blsort(L): 
if len(L) == 0: 
    return [] 
elif L[0] == 0: 
    return [0] + blsort(L[1:]) 
else: 
    return blsort(L[1:]) + [1] 
相關問題