简体   繁体   English

python中的带有字典的尾递归

[英]Tail recursion with dictionary in python

I am trying to implement a tail-recursive algorithm for enumerating sets. 我正在尝试实现一个尾递归算法来枚举集合。 I am searching for lists of numbers with particular properties, but I found a problem in my recursion. 我正在搜索具有特定属性的数字列表,但是在递归中发现了一个问题。

I made a minimal working version with a list (included below) but changing the list to a dictionary and trying the same algorithm gave strange results. 我制作了一个带有列表的最小工作版本(包括在下面),但是将列表更改为字典并尝试使用相同的算法会得出奇怪的结果。

For the purposes of the example,I know I don't need a dictionary but for the non-minimal algorithm I do. 出于示例的目的,我知道我不需要字典,但是我需要非最小算法。 Here is my MWE: 这是我的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

Where is the error that makes the dictionary algorithm repeat entries, but the list one work? 使字典算法重复输入但列表起作用的错误在哪里?

dict.copy is a shallow copy, not a deep copy. dict.copy是浅表副本,而不是深表副本。 That means, the list in the dictionary is not copied, but shared between the copies. 这意味着字典中的列表不会被复制,而是在副本之间共享。 Use copy.deepcopy from the copy -module instead. 请使用copy -module中的copy.deepcopy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM