Python 简单递归函数
这是一个相当简单的任务,我觉得我应该能够做到-但就我的生活而言,我无法理解 我试图编写一个递归函数来复制以下内容:Python 简单递归函数,python,recursion,Python,Recursion,这是一个相当简单的任务,我觉得我应该能够做到-但就我的生活而言,我无法理解 我试图编写一个递归函数来复制以下内容: chars = '0123456789abcdef' for a in chars: for b in chars: for c in chars: for d in chars: print a+b+c+d 寻找一个例子并没有很好的效果 不起作用的代码: chars = 'ABCDEF' def
chars = '0123456789abcdef'
for a in chars:
for b in chars:
for c in chars:
for d in chars:
print a+b+c+d
寻找一个例子并没有很好的效果
不起作用的代码:
chars = 'ABCDEF'
def resu(chars, depth = len(chars)):
for char in chars:
if depth == 0:
return char
return char + resu(chars, depth - 1)
print resu(chars)
如果您有
itertools
,则不需要递归:
from itertools import product
for a,b,c,d in product('abc', repeat=4):
print a+b+c+d
from itertools import combinations_with_replacement
for i in combinations_with_replacement("0123",4):
print(i)
我不打算把它写出来,因为这会违背目的,但这里有一个提示:考虑一下停止递归的条件。以下是关键点:
for char in chars:
return char + recurse(chars, depth - 1)
编辑:这是我忘记Python不是为这类事情而设计的。它需要压平
它不起作用的原因是,最外层循环中的返回将在第一次调用它时结束整个过程
在您的案例中,您真正想要做的是:
def resu(chars, depth = None, prefix=''):
if depth is None:
depth = len(chars)
if depth == 0:
print prefix
return
for ch in chars:
resu(chars, depth - 1, ch + prefix)
请注意,即使是中等长度的字符
,也会产生大量(n!
)行。正如已经指出的,这并不是在Python中获得此结果的最佳方法,但是学习递归是非常有用的
chars = '0123456789abcdef'
def get_combinations(cur_combo=''):
for char in chars:
new_combo = cur_combo+char
if len(new_combo) == 4:
print new_combo
else:
get_combinations(new_combo)
get_combinations()
免责声明:
可能不是一个好例子,但它是递归的,并给出正确的结果。根据@David Heffernan的回答,如果您有
itertools,您也不需要编写自己的组合函数:
from itertools import product
for a,b,c,d in product('abc', repeat=4):
print a+b+c+d
from itertools import combinations_with_replacement
for i in combinations_with_replacement("0123",4):
print(i)
听起来好像有人想让我们做作业不,没有作业,只是好奇。(要是我还在学校就好了!)知道这一点真是太棒了——但我真的在努力理解递归。谢谢:)我认为递归在这里不是很自然。+1:depth-1是这类问题的一个重要提示。基本情况(depth==0)是理解递归的另一个重要提示。我认为添加必要的if
语句可能会有所帮助。我已经掌握了递归结束时的逻辑,但我不确定该怎么做-例如,一个return
会使整个堆栈返回00000
。break
导致堆栈上的最后一个函数返回None
,我得到一个类型错误。我不知道为什么我很难在脑海中想象这个问题:-/@tMC:当您确定这是最后一次调用函数时,只需返回字符。我尝试过了,结果只有00000
。函数的所有副本都会立即返回。+1确实非常好,itertools是一个名副其实的宝库!