簡體   English   中英

使用遞歸迭代列表

[英]Iterate a list using recursion

如何使用遞歸編寫相同的函數?

def replace(thelist,a,b):
"""Returns: a COPY of thelist but with all occurrences of a replaced by b. 

    Example: replace([1,2,3,1], 1, 4) = [4,2,3,4].

Precondition: thelist is a list of ints
              a and b are ints"""

我相信我應該復制原始文件,然后從那里復制一個= b,但是我不知道如何實現。 請幫我解決這個問題,謝謝!

嘗試這個:

def replace(thelist, a, b):
    if not thelist:
        return []
    elif thelist[0] == a:
        return [b] + replace(thelist[1:], a, b)
    else:
        return [thelist[0]] + replace(thelist[1:], a, b)

這是一個遞歸解決方案,可以按預期工作:

replace([1, 2, 3, 1], 1, 4)
=> [4, 2, 3, 4]

暫無
暫無

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

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