Python 递归算法-使用'+';
下面我有一个递归函数,它不断用字母表中的每个小写字母替换Python 递归算法-使用'+';,python,algorithm,recursion,combinations,Python,Algorithm,Recursion,Combinations,下面我有一个递归函数,它不断用字母表中的每个小写字母替换'字符,直到这些可能的小写字母的所有组合都被'字符替换 简单示例: repl\u下划线(“A”) >>[a_a,b_a,c_a……aaA,abA,acA……zzA] 我让这个函数与extend一起构建列表,正如下面的注释所提到的,它反复修改相同的现有列表并完成任务 为了练习,我想重新编写,在每个调用上构建一个新的列表,并将结果传递给后续的递归调用,目的是获得相同的结果 它不起作用,我知道这与我正在为每个调用建立一个新的列表有关,但我认为,由
'
字符,直到这些可能的小写字母的所有组合都被'
字符替换
简单示例:
repl\u下划线(“A”)
>>[a_a,b_a,c_a……aaA,abA,acA……zzA]
我让这个函数与extend一起构建列表,正如下面的注释所提到的,它反复修改相同的现有列表并完成任务
为了练习,我想重新编写,在每个调用上构建一个新的列表,并将结果传递给后续的递归调用,目的是获得相同的结果
它不起作用,我知道这与我正在为每个调用建立一个新的列表有关,但我认为,由于我在每个递归调用上传递了构建版本,所以我可以,因为这些调用将被通知更改
我很难找到它在哪里坏了。我知道我可以通过修改相同的列表(通过可变默认值、全局变量或扩展)使其工作,但我希望在每次递归时建立一个新的干净列表
def repl_underscores(letters,res=None):
if res is None: res = list()
if '_' not in letters: return res
repl = [letters.replace('_',letter,1) for letter in string.ascii_lowercase]
res = res + repl #using += works, due to extending being a mutation (same list referenced at each call)
for each in repl:
repl_underscores(each,res) #trying to pass modified list to keep building up
return res
print(repl_underscores('__DER'))
正如你所猜测的,这一行就是问题所在。每次在递归调用中,它都会分配一个新的本地列表,该列表不会保留对旧列表的引用,因此不会通知调用方更改
幸运的是,您的函数已经返回了列表,所以让我们来捕捉一下:
res = repl_underscores(each,res) #trying to pass modified list to keep building up
正如你所猜测的,这一行就是问题所在。每次在递归调用中,它都会分配一个新的本地列表,该列表不会保留对旧列表的引用,因此不会通知调用方更改
幸运的是,您的函数已经返回了列表,所以让我们来捕捉一下:
res = repl_underscores(each,res) #trying to pass modified list to keep building up
最好不要修改函数参数,而是使用返回的值构建(更具功能性的样式)。只需对代码稍加修改,即可按预期工作 导入字符串
def repl_underscores(letters):
res = list()
if '_' not in letters: return res
repl = [letters.replace('_',letter,1) for letter in string.ascii_lowercase]
res += repl
for each in repl:
res += repl_underscores(each)
return res
print(repl_underscores('__DER'))
最好不要修改函数参数,而是使用返回的值构建(更具功能性的样式)。只需对代码稍加修改,即可按预期工作 导入字符串
def repl_underscores(letters):
res = list()
if '_' not in letters: return res
repl = [letters.replace('_',letter,1) for letter in string.ascii_lowercase]
res += repl
for each in repl:
res += repl_underscores(each)
return res
print(repl_underscores('__DER'))
只需使用不带递归的函数:
from itertools import combinations_with_replacement, chain
def repl_underscores(letters):
result = []
for chars in combinations_with_replacement(string.lowercase, letters.count('_')):
chars = chain(chars,[''])
result.append(''.join(a+next(chars) for a in letters.split('_')))
return result
只需使用不带递归的函数:
from itertools import combinations_with_replacement, chain
def repl_underscores(letters):
result = []
for chars in combinations_with_replacement(string.lowercase, letters.count('_')):
chars = chain(chars,[''])
result.append(''.join(a+next(chars) for a in letters.split('_')))
return result
您是否尝试使用
print
语句查看发生了什么?您是否尝试使用print
语句查看发生了什么?我也喜欢这种方式,谢谢您的回复。我也喜欢这种方式,谢谢您的回复。@Solaxun没问题,我知道这一点,因为几天前我被它咬了。:)@索拉逊:没关系,我知道这一点,因为几天前我被它咬了。:)