簡體   English   中英

python中的帶有字典的尾遞歸

[英]Tail recursion with dictionary in python

我正在嘗試實現一個尾遞歸算法來枚舉集合。 我正在搜索具有特定屬性的數字列表,但是在遞歸中發現了一個問題。

我制作了一個帶有列表的最小工作版本(包括在下面),但是將列表更改為字典並嘗試使用相同的算法會得出奇怪的結果。

出於示例的目的,我知道我不需要字典,但是我需要非最小算法。 這是我的MWE:

# This is the broken algorithm
def find_solutions_dict(actual, may, solutions):

    if (2 not in actual):
        actual[2] = []

    if (len(may) == 0):
        solutions.append(actual.copy())
        return

    # Move onto the next section, excluding the first option                       
    find_solutions_dict(actual, may[1:], solutions)

    new_overlaps = actual.copy()
    new_overlaps[2].append( may[0] )
    find_solutions_dict(new_overlaps, may[1:],solutions)

# However, this one works
def find_solutions_list(actual, may, solutions):
    if (len(may) == 0):
        solutions.append(actual[:])
        return

    find_solutions_list(actual, may[1:], solutions)

    new_overlaps = actual[:]
    new_overlaps.append( may[0])
    find_solutions_list(new_overlaps, may[1:], solutions)

# Test
sol = []
may = [1,2,3]

find_solutions_list([],may, sol)
# Prints all 8 subsets of [1,2,3]
print sol


sol2 = []
find_solutions_dict({}, may, sol2)
# Has 8 entries, but there are many duplicates
print sol2

使字典算法重復輸入但列表起作用的錯誤在哪里?

dict.copy是淺表副本,而不是深表副本。 這意味着字典中的列表不會被復制,而是在副本之間共享。 請使用copy -module中的copy.deepcopy

暫無
暫無

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

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