2014-06-23 64 views
-3

我寫了2個代碼,迭代和遞歸,它們應該返回小於最後一個的第一個數字,即第一個在列表中錯誤的順序。尋找第一個錯誤順序的遞歸代碼Python

迭代代碼,運行良好:

def out_of_order(lst): 
    before = 0 
    for y in lst: 
     if y < before: 
      return y 
     before = y 
print(out_of_order([1,5,17,12,24])) 

返回值是12

遞歸代碼,不工作:

def out_of_orders(lst): 
    if(lst[1]<lst[0]): 
     print(lst[1]) 
     return 
    else: 
     lst1=lst[1:len(lst)]  
     out_of_orders(lst1) 
+1

也許'LEN(LST)'? – Fabricator

+1

你需要'len(lst)== 1'的基本情況,否則你的代碼會拋出一些錯誤。 –

+1

*「不起作用」*是什麼意思?我可以看到一個清晰的'TypeError',所以**爲什麼你不提那個**?! *你做了什麼*來弄清楚?你會得到什麼輸出(或錯誤)? – jonrsharpe

回答

0

你可以使用在Python 2.5起使用的條件語法。

def out_of_orders(lst): 
    return lst[1] if (lst[1] < lst[0]) else out_of_orders(lst[1:]) 

當然你必須測試,如果子陣列是小(以正確的順序一切),所以完整的例子是:

lst = [1,5,17,12,24] 

def out_of_orders(lst): 
    if len(lst) == 1: 
     return None 
    return lst[1] if (lst[1] < lst[0]) else out_of_orders(lst[1:]) 

print out_of_orders(lst) 
0
def out_of_orders(my_list,last_checked=None): 
    if last_checked is not None and last_checked > my_list[0]: 
     return my_list[0] 
    if len(my_list) > 1: 
     return out_of_orders(my_list[1:],my_list[0]) 

我認爲,這將至少工作

+0

我需要只獲得一個字符串到函數 – micmic

+1

out_of_orders([1,2,3,4,5,6,7,4,8,9])' –

+0

@CB :P固定它 –

0

替換:

lst1=lst[1:len(str)] 

有:

lst1=lst[1:] 

它會工作(你可能使用str作爲調試工具,忘記修改你的代碼後刪除它)。

評論:你不應該認爲該列表至少有兩個項目(第一個if)。

def out_of_orders(lst): 
    if(lst[1]<lst[0]): 
     print(lst[1]) 
     return 
    else: 
     lst1=lst[1:]  
     out_of_orders(lst1) 

out_of_orders([1,5,17,12,24]) 

OUTPUT:

12 
0

你遞歸代碼實際執行運行,但不是在所有情況下。你有幾個問題:在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