# Lets the user input a number N between 1 and 10 and a number k
# at most equalt to N!, and outputs the kth permutation of {0, ..., N-1},
# using lexicographic order and counting from 1.
#
# Written by Eric Martin for COMP9021
import sys
from math import factorial
provided_input = input('Enter two strictly positive integers,\n'
' the first one at most equal to 10\n'
' the second one at most equal to first one!: ')
provided_input = provided_input.split()
if len(provided_input) != 2:
print('Incorrect input, giving up.')
sys.exit()
try:
number_range = int(provided_input[0])
rank = int(provided_input[1])
if number_range <= 0 or rank <= 0 or rank > factorial(number_range):
raise ValueError
except:
print('Incorrect input, giving up.')
sys.exit()
solution = ''
Rank = rank
digits = list(range(number_range))
for n in range(number_range - 1, 0, -1):
fact = factorial(n)
i = digits[(Rank - 1) // fact]
Rank %= fact
solution += str(i)
digits.remove(i)
solution += str(digits[0])
print('Lexicographically, the permutation of 0, ..., {} of rank {} is: {}'.
format(number_range - 1, rank, solution))
Resource created Thursday 22 October 2015, 12:03:20 AM.
file: quiz_10_sol.py