【问题标题】:Generate all polynomial terms of certain degree生成一定次数的所有多项式项
【发布时间】:2016-12-01 23:32:14
【问题描述】:

有n个词的列表

ts = ['t1','t2','t3',...,'tn']

有一项任务是实现这些术语的所有可能的 q 长度组合。

因此,对于

ts = ['t1','t2']
q = 4

答案是

[['t1','t1','t1','t1'],['t1','t2','t2','t2'],['t1','t1','t2','t2'],
 ['t1','t1','t1','t2'],['t2','t2','t2','t2']]

这是我的解决方案

powers = np.array(list(itertools.product(*[range(q+1)]*len(ts))))
powers = powers[np.where(np.asarray(map(sum, powers))==q)]
res = map(lambda ps_: flatten([ p*[t] for p,t in zip(ps_,ts) ]), powers)

其中flatten 是从列表列表中生成列表的函数。

虽然有产生预期结果的解决方案,但我想知道是否有更简单的方法来解决问题?

【问题讨论】:

  • 那些不是排列。它们可能是替换的组合。
  • 谢谢,我错过了,更正了。

标签: python arrays python-2.7 numpy itertools


【解决方案1】:

您需要的是替换组合。最简单的解决方案是使用恰当命名的itertools.combinations_with_replacement

>>> list(itertools.combinations_with_replacement(ts,q))
[('t1', 't1', 't1', 't1'),
 ('t1', 't1', 't1', 't2'),
 ('t1', 't1', 't2', 't2'),
 ('t1', 't2', 't2', 't2'),
 ('t2', 't2', 't2', 't2')]

【讨论】:

  • 谢谢,这就是我要找的!
  • @tarashypka 不用担心,在您了解它是什么之前,很难确定正确的名称:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 2015-05-13
  • 2021-11-01
  • 2011-06-22
相关资源
最近更新 更多