首页 > 解决方案 > 排列的东西

问题描述

如何编写一个函数(在 Python 中):

如果我们取 A、B 和 C 的所有排列:ABC、ACB、BAC、BCA、CAB、CBA

该函数将获取一个索引并返回该索引的排列。

例如 F("ABC", 4) 将返回 "BCA"

对于非常大的排列集,它应该在合理的时间内运行。

标签: pythonpermutation

解决方案


您可以解析/过滤 的结果itertools.permutations(),因为无法直接索引生成器。像这样的函数可以做到这一点:

from itertools import permutations

def nth_permutation(items, n):
    i = 0
    perms = permutations(items)
    try:
        next_perm = next(perms)
        while i < n:
           next_perm = next(perms)
           i += 1
    except StopIteration:
        # implement error behavior here, if n > number of permutations. 
        # For now we just return the default value, None
        # you might instead try throwing an IndexError
        return None
    return next_perm

(注意,索引的排列4是 "CAB" - "BCA" 是 index 3


推荐阅读