Recursive function with yield doesn't return anything

后端 未结 2 687
被撕碎了的回忆
被撕碎了的回忆 2021-01-16 09:46

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 y

2条回答
  •  借酒劲吻你
    2021-01-16 10:34

    Your line perm(s,p+1,ii) doesn't do anything, really: it's just like typing

    >>> perm("fred")
    
    

    If you yield from that call, though, i.e.

            for subperm in perm(s, p+1, ii):
                yield subperm
    

    Then you'd get

    >>> 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.

    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: right now you don't handle the one-character case.

提交回复
热议问题