簡體   English   中英

Python - 划分列表並維護原始索引(遞歸)

[英]Python - dividing a list and maintaining the original index (Recursion)

我有作業,我必須使用遞歸來查找列表中所有出現的數字/字母/單詞,並在原始列表中返回它們的索引。關於遞歸,即使在發現第一次出現后,也可以選擇繼續檢查列表。

應該看起來像這樣:

>>> 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] ..這是真的,對於分割列表..這樣我永遠不會得到原始索引..謝謝 - 如果這已經存在,我很抱歉因為我已經搜索過但沒有找到。

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

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

布置作業的目的通常是讓您可以探索問題並從中學習。 在這種情況下,遞歸通常對初學者來說很難。

遞歸的重點是從較小問題的解決方案中構建較大問題的答案。 所以最好從最小的開始:

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。那是因為它們是較小列表中的索引。 如果某項在較小列表中的索引為0 ,則意味着它在最大列表中的索引實際上為1 (這是您的程序缺少的主要部分),因此:

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

並返回完整答案:

    return occurrences

我希望這對你有所幫助,這樣你就可以自己做下一個家庭作業了。

這里有幾種解決方案:

一口氣,丑陋,但工作:

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)))]

更漂亮,但帶有隱藏的索引參數:

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)

這個問題有一個非常簡單的解決方案,即使你使用遞歸來解決賦值:

>>> 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]
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM