# # Prints all permutations. # def permutation(s, b, e): if b+1 == e: print(s) else: for i in range(b, e-1): permutation(s, b+1, e) c = s[i+1] s[i+1] = s[i] s[i] = s[b] s[b] = c permutation(s, b+1, e) c = s[b] s[b] = s[e-1] s[e-1] = c # # Prints all permutations. But in addition doesn't print # multiple instances of same value. # e.g. abb bab bba ( doesn't print two abb ) # def permutation2(s): print(s) l = len(s) while True: i = l-1 while True: ii = i i = i - 1 if ord(s[i]) < ord(s[ii]): j = l-1 while ord(s[i]) >= ord(s[j]): j = j - 1 s[i], s[j] = s[j], s[i] s[ii:l] = s[ii:l][::-1] print(s) break if i == 0: return if __name__ == "__main__": s = ['a', 'b', 'c', 'd', 'e', 'e'] permutation(s, 0, len(s)) print("--------------------------------------------") permutation2(s)