Warm tip: This article is reproduced from serverfault.com, please click

windows-如何在python中进行especific组合?

(windows - How make a especific combinations in python?)

发布于 2020-11-28 12:12:44

我正在尝试进行特定的组合,以便通过添加以下规格将其总计为“ 4”:

a+a+a+a+a+a+a+a = 0.5 per/unit  = (In total it sum:) 4
b+b+b+b = 1 per/unit  = (In total it sum:) 4
c+c = 2 per/unit  = (In total it sum:) 4

这样,我想知道结果并在屏幕上打印组合:

a+a+a+a+a+a+a+a = 4
a+a+a+a+a+a+b = 4
a+a+a+a+b+b = 4
a+a+b+b+b = 4
a+a+a+a+a+a+c = 4
a+a+b+c = 4
a+a+c+b = 4
b+a+a+a+a+a+a = 4
b+b+a+a+a+a = 4
b+b+b+a+a = 4
b+b+c = 4
b+c+a+a = 4
b+a+c = 4
b+c+a = 4
c+a+a+a+a = 4
c+b+a+a = 4
c+a+a+b = 4

我的代码:

from itertools import combinations
numbers=[2,4,8]
for c in combinations(numbers, 3):
    print(c)

有没有办法做到这一点?非常感谢你的自述。

Questioner
Ulises Antonio Chávez
Viewed
0
Marc 2020-11-28 22:54:36

我将尝试以一种有教义的方式回答你的问题,而不提供完整的代码(如你在上面的注释中所要求的)。

  1. 组合方法

直接的解决方案是只看数字数组在不同长度下的可能组合。遍历长度和组合,你可以检查这些元素上的总和是否能解决你的问题。

你应该看一下该函数,itertools.combinations_with_replacement因为它允许每个元素多次出现。

from itertools import combinations_with_replacement

numbers=[2,4,8]
for length in [3]:
   for c in combinations_with_replacement(numbers, length):
      print(c, f"sum {sum(c)}")

> (2, 2, 2) sum 6
> (2, 2, 4) sum 8
> (2, 2, 8) sum 12
> (2, 4, 4) sum 10
> (2, 4, 8) sum 14
> (2, 8, 8) sum 18
> (4, 4, 4) sum 12
> (4, 4, 8) sum 16
> (4, 8, 8) sum 20
> (8, 8, 8) sum 24

你必须相应地指定长度数组,并添加一个if子句以进行打印。

  1. 功能方法:

假设你要查找的函数定义为def calcComb(sum,numbers): ...返回你尝试过的组合字符串。

解决此问题的典型功能解决方案是递归调用一个内部函数rec(sumRest,numRest,textComb)该函数跟踪你所累积的总和以及要测试的组合(此处为字符串格式)。骨骼结构如下所示:

def rec(sumRest,numRest,textComb):
 if  ... :  return ... 
 elif ... : return ...
 else :
    newText = ...
    return rec(sumRest-numRest[0],numRest,textComb+newText) 
          + rec(sumRest,numRest[1:],textComb) 

编辑 :

上面的方法是问题的直接实现,并且未针对性能进行优化。如果你的问题扩大了,你可能有兴趣保存以前的计算步骤的状态(动态方法)或将中间结果缓存在假想的(内存化)中。