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