具有yield的递归函数不返回任何内容 [英] Recursive function with yield doesn't return anything
问题描述
我正在尝试创建用于置换目的的生成器.我知道还有其他方法可以在Python中执行此操作,但这是其他方法.不幸的是,我无法产生这些价值.你能帮忙吗?
I am trying to create a generator for permutation purpose. I know there are other ways to do that in Python but this is for something else. Unfortunately, I am not able to yield the values. Can you help?
def perm(s,p=0,ii=0):
l=len(s)
s=list(s)
if(l==1):
print ''.join(s)
elif((l-p)==2):
yield ''.join(s)
yield ''.join([''.join(s[:-2]),s[-1],s[-2]])
else:
for i in range(p,l):
tmp=s[p]
s[p]=s[i]
s[i]=tmp
perm(s,p+1,ii)
推荐答案
您的行perm(s,p+1,ii)
并没有执行任何操作,实际上:就像键入
Your line perm(s,p+1,ii)
doesn't do anything, really: it's just like typing
>>> perm("fred")
<generator object perm at 0xb72b9cd4>
但是,如果您从该通话中获得收益,即
If you yield from that call, though, i.e.
for subperm in perm(s, p+1, ii):
yield subperm
那么你会得到
>>> list(perm("abc"))
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
>>> list(perm("abcd"))
['abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba', 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba']
>>> len(_)
24
>>> len(set(perm("abcd")))
24
看起来还可以.除此之外,我还没有测试过代码.
which looks okay. I haven't tested the code beyond that.
顺便说一句,您可以将s[i]
和s[p]
与s[i], s[p] = s[p], s[i]
交换;不需要tmp
变量.
BTW, you can swap s[i]
and s[p]
with s[i], s[p] = s[p], s[i]
; no need for a tmp
variable.
PS:现在您不处理一个字符的情况.
PS: right now you don't handle the one-character case.
这篇关于具有yield的递归函数不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!