python中带字典的尾部递归
我试图实现一个用于枚举集合的尾部递归算法。我正在搜索具有特定属性的数字列表,但在递归中发现了一个问题 我用一个列表(包括在下面)制作了一个最小的工作版本,但将列表更改为字典并尝试相同的算法会产生奇怪的结果 就本例而言,我知道我不需要字典,但对于非最小算法,我需要字典。这是我的MWE:python中带字典的尾部递归,python,dictionary,tail-recursion,Python,Dictionary,Tail Recursion,我试图实现一个用于枚举集合的尾部递归算法。我正在搜索具有特定属性的数字列表,但在递归中发现了一个问题 我用一个列表(包括在下面)制作了一个最小的工作版本,但将列表更改为字典并尝试相同的算法会产生奇怪的结果 就本例而言,我知道我不需要字典,但对于非最小算法,我需要字典。这是我的MWE: # This is the broken algorithm def find_solutions_dict(actual, may, solutions): if (2 not in actual):
# 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
-模块中的copy.deepcopy
。如果不是python中的函数,则不需要parenif(len(may)==0):
更好if-may:
。请注意,python不会优化尾部递归调用,因此,当您完成尾部递归函数的编写时,最好将其转换为循环以获得更好的性能(一旦以尾部调用的形式出现,就很简单)。