Skip to content

Instantly share code, notes, and snippets.

@jgxvx
Created October 11, 2013 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgxvx/6936178 to your computer and use it in GitHub Desktop.
Save jgxvx/6936178 to your computer and use it in GitHub Desktop.
Permutations in Python
# coding=utf-8
import copy
import datetime
term = 'abcdefghij'
o = 0
def permutations(tokens, p, n):
global o
o += 1
if 1 == n:
p.append([tokens[0]])
else:
new_permutations = []
for i in range(len(p)):
o += 1
permutation = p[i]
new_permutations.append(permutation)
for j in range(1, n):
o += 1
new_permutations.append(copy.copy(permutation))
p = new_permutations
token = tokens[n-1]
index = -1
for permutation in p:
o += 1
index += 1
permutation.insert(index % n, token)
if len(tokens) <= n:
return p
else:
return permutations(tokens, p, n+1)
t_start = datetime.datetime.now()
p = permutations([token for token in term], [], 1)
t_end = datetime.datetime.now()
t = t_end - t_start
print("O(%d) = %d") % (len(term), o)
print("t = %.2fms") % (t.microseconds / 1000.0)
#for permutation in p:
# print(''.join(permutation))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment