Python String Permutations Up To 2 Letter Changes Per Permutation -
how make permutation generator in python limit changes 2 letters?
example:
create_perm('cow')
returns
['cwo', 'woc', 'ocw']
but not 'wco'
since mean 3 letters have changed position.
if 2 letters allowed change, boils down swapping 2 letters:
from itertools import combinations def changetwo(s): i,j in combinations(range(len(s)), 2): res = list(s) res[i], res[j] = res[j], res[i] yield ''.join(res)
demo:
>>> list(changetwo('cow')) ['ocw', 'woc', 'cwo'] >>> x in changetwo('1234'): ... x ... '2134' '3214' '4231' '1324' '1432' '1243'
Comments
Post a Comment