n项的组合数
是否有代数公式可以告诉我ntemrs的不同组合?
如果我有:
{0: ['Hello!']}
{1: ['Welcome']}
{2: ['to']}
所有的组合都是:
['Hello!', 'Welcome', 'to'],
['Hello!', 'to', 'Welcome'],
['Welcome', 'Hello!', 'to'],
['Welcome', 'to', 'Hello!'],
['to', 'Hello!', 'Welcome'],
['to', 'Welcome', 'Hello!'],
但是描述这个的公式是什么?然后我会使用公式来编写我的程序,并从我可用的单词中创建所有可能的三元组。我看过这个链接,但还没有想出答案:
https://www.mathsisfun.com/combinatorics/combinations-permutations.html
回答
您所描述的是n 个对象的排列数。有n个!= 1 × 2 × ... × n(也称为n factorial)这样的排列。
回答
您需要置换的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', 'B', 'C', 'D']
z = permutations(lst, len(last))
print(list(z))