gpt4 book ai didi

python - 在递归函数中用尾递归替换 for 循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:40:11 24 4
gpt4 key购买 nike

我正在尝试使以下函数完全尾递归,例如把那个讨厌的 for 循环从那里拿走。原因是我试图轻松地将解决方案转换为涉及使用显式堆栈的迭代解决方案。请指教。

def permutations(A):
P = []
P2 = []
permutations_recursive(A, [], P)
permutations_tail_recursive(A, [], P2, 0)
print(P2)
return P

def permutations_recursive(first, last, perms):
if len(first) == 0:
perms.append(last)
else:
for i in range(len(first)):
permutations_recursive(
first[:i] + first[i+1:],
last + [first[i]],
perms)

最佳答案

关闭迭代模拟:

def permutations(A):
P = []
permutationsI(A, P)
print(P)

def permutationsI(A, perms):
stack = [(A, [])]
while len(stack):
first, last = stack.pop()
if len(first):
for i in range(len(first)):
stack.append((first[:i] + first[i+1:],last + [first[i]]))
else:
perms.append(last)

permutations([1,2,3])
>>[[3, 2, 1], [3, 1, 2], [2, 3, 1], [2, 1, 3], [1, 3, 2], [1, 2, 3]]

关于python - 在递归函数中用尾递归替换 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com