繁体   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