Project Euler #24: Lexicographic permutations

  • + 0 comments
    from math import factorial
    
    def nth_permutation(word,n):
        factoradic=[]
        word=list(word)
        for i in range(len(word) - 1, -1, -1):
            f=factorial(i)
            factoradic.append(n//f)
            n=n%f  
        return ''.join([word.pop(j) for j in factoradic])
    t=int(input().strip())
    for _ in range(t):
        n=int(input().strip())
        word='abcdefghijklm'
        print(nth_permutation(word,n-1))