I have a list like this: a,b,c,d,e,f,g. And I want to calculate the permutation number 57 in a list of two elements ( in this case is f,g ). But I do not want to permute the list 57 times, I want a math formula able to calculate permutation number 57 in python.
I have tried this in python but it doesn't works and gives me the following result: ['a', 'b', 'e', 'd', 'f', 'c', 'g'], the correct result must be: ['f', 'g']
import math
def calculate_kth_permutation(lst, k):
n = len(lst)
if k >= math.factorial(n):
raise ValueError("Index k is out of range.")
result = []
for i in range(n, 0, -1):
fact = math.factorial(i - 1)
quotient, k = divmod(k, fact)
result.append(lst.pop(quotient))
return result
# Example usage:
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
index = 56 # 0-based index for the 57th permutation
permutation = calculate_kth_permutation(my_list, index)
print(permutation)
Someone can help me find the correct formula?