Skip to content

Instantly share code, notes, and snippets.

@markgarg
Created June 25, 2017 21:23
Show Gist options
  • Save markgarg/91b86aaa810edfcdf8084233883e7986 to your computer and use it in GitHub Desktop.
Save markgarg/91b86aaa810edfcdf8084233883e7986 to your computer and use it in GitHub Desktop.
Permutation generator - first attempt
"""
Given an integer 'n', create a generator that will return a new permutation
of the integers between 1 and n, until all the permutations have been
exhausted.
Ex: input: 3
output: 123, 132, 321, 231, 312, 213
"""
def generate_permutations_for_number_of_digits(n):
if n <= 1:
return 1
digit_list = [x for x in range(1, n+1)]
return generate_permutations_for(digit_list=digit_list)
def generate_permutations_for(digit_list):
num_of_digits = len(digit_list)
if num_of_digits == 2:
base = int(str(digit_list[0]) + str(digit_list[1]))
yield base
swapped_base = int(str(digit_list[1]) + str(digit_list[0]))
yield swapped_base
else:
for x in range(1, num_of_digits + 1):
fixed_digit = digit_list[x-1]
temp_list = digit_list[:]
del temp_list[x-1]
for y in generate_permutations_for(digit_list=temp_list):
num_so_far = int(str(fixed_digit) + str(y))
yield num_so_far
print(list(generate_permutations_for_number_of_digits(5)))
print(len(list(generate_permutations_for_number_of_digits(5))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment