Project Euler #24: Lexicographic permutations

  • + 0 comments

    in python3

    def factorial(n): result = 1 for i in range(1, n+1): result *= i return result

    def nth_lexicographic_permutation(n, word): n -= 1 # Adjusting for 0-based indexing factorials = [factorial(i) for i in range(len(word))] result = "" available = list(word) for i in range(len(word), 0, -1): index = n // factorials[i-1] n = n % factorials[i-1] result += available.pop(index) return result

    word = "abcdefghijklm" for _ in range(int(input().strip()) n = int(input().strip()) result = nth_lexicographic_permutation(n, word) print(result)

        index = n // factorials[i-1]
        n = n % factorials[i-1]
        result += available.pop(index)
    return result