【问题标题】:Number of combinations of n termsn 项的组合数
【发布时间】:2021-02-06 00:27:29
【问题描述】:

有代数公式告诉我n temrs 的不同组合吗?

如果我有:

{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

【问题讨论】:

  • 你能举个例子,不是所有的列表都是一个元素吗?
  • 应该是 3x2x1。第一个位置有 3 个选择,第二个有 2 个,第三个只有 1 个。
  • 但是我认为你的第 5 行和第 6 行应该以 to 开头,如果我没听错的话?
  • 是的,抱歉,我正在修复它

标签: python algorithm math combinations discrete-mathematics


【解决方案1】:

您需要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))

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多