Python 3.x 如何存储中间递归结果
我想得到同样的结果,这是使用打印功能打印在下面的代码作为功能结果。如果我在循环中使用return语句,那么循环就会被破坏,并且我永远不会到达大于0的索引。 如何将中间结果存储在局部变量中,并最终作为函数结果返回Python 3.x 如何存储中间递归结果,python-3.x,recursion,Python 3.x,Recursion,我想得到同样的结果,这是使用打印功能打印在下面的代码作为功能结果。如果我在循环中使用return语句,那么循环就会被破坏,并且我永远不会到达大于0的索引。 如何将中间结果存储在局部变量中,并最终作为函数结果返回 l = list("ABCD") def remel(l, pos): res = l[:] del res[pos] return(res) def f(l): if len(l) == 1: res = l retu
l = list("ABCD")
def remel(l, pos):
res = l[:]
del res[pos]
return(res)
def f(l):
if len(l) == 1:
res = l
return(res)
else:
for i in range(len(l)):
res = [l[i]] + f(remel(l, i))
print(res) # store this and pass on how?
return(res)
f(l)
return关键字立即停止函数的执行,并跳回调用函数的位置继续执行。
也就是说,如果您只想存储res的值,那么可以用以下代码替换函数的最后两行-
list_where_you_want_to_store.append(res) # Declare the list first, then keep appending res.
return(list_where_you_want_to_store)
接下来,您可以随时使用列表中存储的值。return关键字立即停止函数的执行,并跳回到调用函数的位置继续执行。
也就是说,如果您只想存储res的值,那么可以用以下代码替换函数的最后两行-
list_where_you_want_to_store.append(res) # Declare the list first, then keep appending res.
return(list_where_you_want_to_store)
接下来,您可以随时使用列表中存储的值。您可以使用这些值访问中间递归结果。根据讨论中给出的示例,假设您正在计算前n个数字的和:
这里,正在运行的_总计被传递给每个调用,因此您可以通过访问此变量访问中间递归调用:
tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
# Returns 15
您可以使用访问中间递归结果。根据讨论中给出的示例,假设您正在计算前n个数字的和:
这里,正在运行的_总计被传递给每个调用,因此您可以通过访问此变量访问中间递归调用:
tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
# Returns 15
最终解决了这个问题:
l = list("ABCD")
def remel(l, pos):
res = l[:]
del res[pos]
return(res)
def f(l, mem = [], minlen = 1):
if len(l) == minlen:
res = l
if res not in mem: # no duplicates
mem.append(res)
return(res, mem)
else:
for i in range(len(l)):
res_next = f(remel(l, i), mem)
res = [l[i]] + res_next[0]
res.sort() # sort
if not mem:
mem = [res]
elif res not in mem: # no duplicates
mem.append(res)
return(res, mem)
print(f(l)[1])
#['D']
#['C', 'D']
#['C']
#['B', 'C', 'D']
#['B', 'D']
#['B']
#['B', 'C']
#['A', 'B', 'C', 'D']
#['A', 'C', 'D']
#['A', 'D']
#['A']
#['A', 'C']
#['A', 'B', 'D']
#['A', 'B']
#['A', 'B', 'C']
最终解决了这个问题:
l = list("ABCD")
def remel(l, pos):
res = l[:]
del res[pos]
return(res)
def f(l, mem = [], minlen = 1):
if len(l) == minlen:
res = l
if res not in mem: # no duplicates
mem.append(res)
return(res, mem)
else:
for i in range(len(l)):
res_next = f(remel(l, i), mem)
res = [l[i]] + res_next[0]
res.sort() # sort
if not mem:
mem = [res]
elif res not in mem: # no duplicates
mem.append(res)
return(res, mem)
print(f(l)[1])
#['D']
#['C', 'D']
#['C']
#['B', 'C', 'D']
#['B', 'D']
#['B']
#['B', 'C']
#['A', 'B', 'C', 'D']
#['A', 'C', 'D']
#['A', 'D']
#['A']
#['A', 'C']
#['A', 'B', 'D']
#['A', 'B']
#['A', 'B', 'C']