Bha*_*rat 7 python algorithm recursion
我在这里提到了几个关于递归的问题但是我无法理解递归是如何适用于这个特定问题的:递归程序在Python中获取字符串中的所有字符组合:
st= []
def combi(prefix, s):
if len(s)==0: return
else:
st.append(prefix+s[0])
''' printing values so that I can see what happens at each stage '''
print "s[0]=",s[0]
print "s[1:]=",s[1:]
print "prefix=",prefix
print "prefix+s[0]=",prefix+s[0]
print "st=",st
combi(prefix+s[0],s[1:])
combi(prefix,s[1:])
return st
print combi("",'abc')
Run Code Online (Sandbox Code Playgroud)
我已经打印了值,以便我可以看到发生了什么.这是输出:
s[0]= a
s[1:]= bc
prefix=
prefix+s[0]= a
st= ['a']
s[0]= b
s[1:]= c
prefix= a
prefix+s[0]= ab
st= ['a', 'ab']
s[0]= c
s[1:]=
prefix= ab
prefix+s[0]= abc
st= ['a', 'ab', 'abc']
s[0]= c
s[1:]=
prefix= a ----> How did prefix become 'a' here. Shouldn't it be 'abc' ?
prefix+s[0]= ac
st= ['a', 'ab', 'abc', 'ac']
.........
.........
['a', 'ab', 'abc', 'ac', 'b', 'bc', 'c'] # final output
Run Code Online (Sandbox Code Playgroud)
完整输出:http://pastebin.com/Lg3pLGtP
正如我在输出中所示,前缀如何成为'ab'?
我试图可视化组合的递归调用(前缀+ s [0],s [1:]).我明白了吗?
那里有一个Python模块为
生成:
from rcviz import callgraph, viz
st= []
@viz
def combi(prefix, s):
if len(s)==0:
return
else:
st.append(prefix+s[0])
combi.track(st = st) #track st in rcviz
combi(prefix+s[0],s[1:])
combi(prefix,s[1:])
return st
print combi("",'abc')
callgraph.render("combi.png")
Run Code Online (Sandbox Code Playgroud)