【问题标题】:Building dict combinations to match a target sum in Python构建字典组合以匹配 Python 中的目标总和
【发布时间】:2014-08-09 23:15:41
【问题描述】:

我有一个由 N 个整数值组成的字典,如下所示:

units = {'trooper':2, 'tank':10, 'helicopter':12}

而且我还有一个目标值……比如 120。

我正在尝试找出方程式的所有可能结果:

a*units['trooper'] + b*units['tank'] + c*units['helicopter'] = 120

所以结果看起来像:

60*trooper
55*trooper + 1*tank
54*trooper + 1*helicopter

依此类推,字典中 N 个键的所有可能组合...

我该如何构建这个?

【问题讨论】:

标签: python dictionary combinations reduce


【解决方案1】:

如果您知道这些问题的名称,那么搜索这些问题的解决方案是最容易的。谷歌Diophantine equations

在 Python 世界中,您可以使用包含丢番图方程求解器的 Sympy package。该软件包可以解决您的问题:

from sympy import symbols
from sympy.solvers.diophantine import diop_solve

trooper, tank, helicopter = symbols('trooper tank helicopter', integer=True)
print diop_solve(2*trooper + 10*tank + 12*helicopter - 120)

它输出:

(5*t - trooper + 60, -6*t + trooper - 60, trooper)

您也可以搜索"ways to make change",这是表达问题的另一种方式。一个相关的问题称为The Knapsack Problem,众所周知,它很难解决。求解线性丢番图方程的一般系统背后的数学有点复杂。以下是一些资源:

【讨论】:

  • 不确定这是否是“技术上”的答案 - 但它因协助 OP 处理搜索词而得到了我的 +1
  • 感谢您提供的非常翔实的回答。不过我还是有点困惑:如何解释 diop_solve 函数的结果? "(5*t - trooper + 60, -6*t + trooper - 60, trooper)" 我如何从中生成所有可能的组合?
【解决方案2】:

这样的事情适用于目标值的小值:

units = {'trooper':2, 'tank':10, 'helicopter':12}
total = 120
for i in range(int(total/units['helicopter'])):
    for j in range(int(total/units['tank'])):
            if (total-units['helicopter']*i-units['tank']*j)%2==0 and (total-units['helicopter']*i-units['tank']*j)>0:
                print ((total-units['helicopter']*i-units['tank']*j)/2,j,i)

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 2021-01-10
    • 2017-10-09
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2012-06-21
    相关资源
    最近更新 更多