n项的组合数

问题描述

是否有代数公式可以告诉我 n 项的不同组合?

如果我有:

{0: ['Hello!']}

{1: ['Welcome']}

{2: ['to']}

所有组合为:

['Hello!','Welcome','to'],['Hello!','to','Welcome'],['Welcome','Hello!','Hello!'],['to',

但是描述这个的公式是什么?然后我会使用公式来编写我的程序,并从我可用的单词中创建所有可能的三元组。我看过这个链接,但还没有想出答案:

https://www.mathsisfun.com/combinatorics/combinations-permutations.html

解决方法

您所描述的是n 个对象的排列数。有n! = 1 × 2 × ... × n(也称为n阶乘)这样的排列。

,

您需要 n 项的排列itertools 有一个排列方法。您可以按如下方式使用它:

import itertools

lst = ['A','B','C','D']
z = itertools.permutations(lst,len(lst))

print(list(z))

如果您想了解更多信息:https://docs.python.org/3/library/itertools.html#itertools.permutations

import itertools

def permutations(iterable,r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in itertools.product(range(n),repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)

lst = ['A','D']
z = permutations(lst,len(last))

print(list(z))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...