2012-11-17 28 views
2

我有作業,其中我必須使用遞歸來查找列表中的數字/字母/單詞的所有出現並返回其原始列表中的索引。已經搜索這個網站的前面回答的問題,但我找不到關於與選擇繼續甚至第一occurances已經發現後檢查清單遞歸任何回答..Python - 劃分列表並維護原始索引(遞歸)

應該像這樣幾乎:

>>> find_value([4,7,5,3,2,5,3,7,8,6,5,6], 5) 
[2,5,10] 

我的代碼到目前爲止是這樣的:

def find_all(x,y): 
    if len(x) == 1 and x[0] == y: 
     return [i for i, y in enumerate(x)] 
    return find_all(x[1:],y) 

雖然它只是最小化列表,並給出了與索引相同的[0] ...這是真實的,對於分割列表..這種方式我永遠不會得到原始索引.. 謝謝 - if這已經存在,我很抱歉,我已經搜索,找不到。

+0

如果你處理Lisp中,你能明白我的回答的靈感。 –

回答

1

分配作業的重點通常是讓您可以探索問題並從中學習。在這種情況下,它是遞歸的,對於初學者來說通常很困難。

遞歸的要點是從較小問題的解決方案構建一個更大問題的答案。所以,最好是用最小的一個可能的開始:

def find_all(haystack, needle): 
    if not haystack: 
     # no occurrences can happen 
     return [] 

如果該列表不爲空,我們可以檢查,如果第一個元素就是我們正在尋找的:

if haystack[0] == needle: 
     occurrences = [0] # the index of the first element is always 0 
    else: 
     occurrences = [] 

我們將還需要解決小問題:

recursive_occurences = find_all(haystack[1:], needle) 

現在你已經注意到問題是,返回的索引始終爲0。這是因爲他們在小指數er列表。如果一個項目在一個較小的列表索引0,這意味着它在最大列表索引實際上是1(這是你的程序缺失的主要部分),即:

for x in recursive_occurences: 
     occurrences.append(x+1) 

,並返回完整的答案:

return occurrences 

我希望這可以幫助你一點,所以你可以做你自己的下一個作業。

+0

非常感謝,幫助了很多,現在我只需要研究一下,找出它! – Spectalecy

2

下面是一個簡單的非遞歸解決方案:

def find_value(l, lookfor): 
    return [i for i, v in enumerate(l) if v == lookfor] 

作爲一件爲你的功課建議 - 只是在列表中傳遞的進展作爲一個可選的第三個參數find_all

def find_value(list, lookfor, position=0) 

...並在每次遞歸時加一個到position

+0

雖然如我所說,遞歸必須使用..因爲它是一種實踐homeworK:P – Spectalecy

+4

@Spectalecy:請參閱我的編輯。不要指望人們爲你做所有的功課。 – Eric

+0

我沒有,雖然我之前提到它必須是遞歸的,但在這裏並不需要循環使用,我知道這些選項。 我再次重視你的幫助,但不需要有敵意。 – Spectalecy

0

這裏有幾種解決方案:

一氣呵成

,難看,但工作:

def find_value(lst, elt): 
    return [x + 1 
      for x in ([] if not lst else 
         (([-1] if lst[0] == elt else []) + 
         find_value(lst[1:], elt)))] 

漂亮,但隱藏的指數PARAM:

def find_value(lst, elt, idx=0): 
    return [] if not lst else \ 
      (([idx] if lst[0] == elt else []) + 
      find_value(lst[1:], elt, idx + 1)) 

漂亮?長着內遞歸函數...更易維護?

def find_value(lst, elt): 
    def _rec(lst, elt, idx): 
     if not lst: 
      return [] 
     res = [idx] if lst[0] == elt else [] 
     return res + _rec(lst[1:], elt, idx + 1) 
    return _rec(lst, elt, idx=0) 
0

有一個很簡單的解決這個問題,即使您正在使用遞歸來解決分配:

>>> def find_value(array, value): 
    *head, tail = array 
    array = find_value(head, value) if head else [] 
    return array + [len(head)] if tail == value else array 

>>> find_value([4, 7, 5, 3, 2, 5, 3, 7, 8, 6, 5, 6], 5) 
[2, 5, 10] 
>>>