Stand With Ukraine

Wednesday, December 23, 2009

Permutations

It is time to write something about programming. Here I want to present a function implemented in python which returns the list of permutations of the given string.

#return the list of the permutations of s
def get_permutations(s):
result = []
if len(s) == 1:
result.append(s)
return result

for i in range(0,len(s)):
s_tmp = s.replace(s[i],s[0])[1:]
subset_permuts = get_permutations(s_tmp)
for perm in subset_permuts:
result.append( s[i] + perm )
return result

It takes 16.5364508629 seconds in order to find the permutations of the string '1234567890'.
For the code

print get_permutations('123');
print 'Execution time: ', time.time() - t0, ' s'

The output is following:
['123', '132', '213', '231', '321', '312']
Execution time: 5.88893890381e-05 s

No comments: