Permutation function
- def permute(s):
- n = len(s)
- if n <= 1:
- return s
- elif n == 2:
- return [''.join([s[0],s[1]]),''.join([s[1],s[0]])]
- else:# n > 2
- snew = []
- for i in range(n):
- a = [k for k in s]#copy s to a
- #print(s)
- ele = a.pop(i)
- for p in permute(a):
- q = ele + p
- if not(q in snew):
- snew.append(q)
- return snew
- def permutations(string):
- s = [ele for ele in string]
- return permute(s)
This code is not efficientcy
Using set() in python rather list()
def permutations(string):
if len(string) == 1: return set(string)
first = string[0]
rest = permutations(string[1:])
result = set()
for i in range(0, len(string)):
for p in rest:
result.add(p[0:i] + first + p[i:])
return result
Or intertool library:
import itertools def permutations(string): return list("".join(p) for p in set(itertools.permutations(string)))
Comments
Post a Comment