ASCII字符溢出的排列中的第N个位置

时间:2019-05-23 02:13:56

标签: python permutation

我正在尝试编写第n位算法,并且打算包含ASCII标准字符表。目前,对于阶乘大小,它似乎太大了(导致溢出)。

是否有更好的方法来进行我的工作,以便以排列的排列顺序找到第n个位置。

import functools
from typing import List, Any


def perm(sequence: len) -> int:
    """ Compute factorial length
    """
    return functools.reduce(lambda x, y: x * y, range(1, len(sequence) + 1), 1)


def nth_perm(sequence, index: object) -> list:
    """ Returns the nth lex permutation
    """
    sequence = list(sequence[:])
    result: List[Any] = []
    factorial = perm(sequence)
    index %= factorial
    while sequence:
        factorial = factorial / len(sequence)
        choice, index = index // factorial, index % factorial
        result += [sequence.pop(int(choice))]
    return result


def position(p: int):
    return nth_perm([i for i in range(255)], p)


print(position(3))

我承认我是Python的新手,并且已经有一段时间没有编码了。我希望能够从1..255中找到第n个位置的排列。

错误

OverflowError: integer division result too large for a float

0 个答案:

没有答案