你遞歸代碼實際執行運行,但不是在所有情況下。你有幾個問題:在Python
def out_of_orders(lst):
if(lst[1]<lst[0]): # what if len(lst) < 2?
print(lst[1]) # why print the number...
return # ... then return nothing?
else: # why 'else' - if the 'if' was met, you've already returned
lst1=lst[1:len(lst)] # no need to assign this one line before using it
out_of_orders(lst1) # call recursively but ignore value returned
功能一般應return
而非print
的價值 - 它然後由主叫方,以決定是否需要用戶反饋。這個功能真的應該是這樣的:
def out_of_order(lst):
"""Return the first number in lst that's out of order."""
if len(lst) > 1:
if lst[0] > lst[1]:
return lst[1]
return out_of_orders(lst[1:])
在片[1:]
手段「從指標1,直到我們用完了」。請注意,這將返回第一個「無序」號碼,或None
。用法示例:
>>> print(out_of_order([1, 2, 3]))
None
>>> print(out_of_order([1, 3, 2]))
2
>>> print(out_of_order([3, 1, 2]))
1
現在主叫方獲得,以決定是否print
值,或在進一步的計算中使用它。
此外,您的迭代版本有優勢情況下的問題,可以考慮:
>>> out_of_order([-3, -2, -1])
-3
一個可能的解決辦法:
def out_of_order(lst):
before = None
for y in lst:
if before is not None and y < before:
return y
before = y
也許'LEN(LST)'? – Fabricator
你需要'len(lst)== 1'的基本情況,否則你的代碼會拋出一些錯誤。 –
*「不起作用」*是什麼意思?我可以看到一個清晰的'TypeError',所以**爲什麼你不提那個**?! *你做了什麼*來弄清楚?你會得到什麼輸出(或錯誤)? – jonrsharpe