Py学习  »  Python

使用Python中的itertools将不同硬币命名的组合汇总为目标值

tetris555 • 3 年前 • 1418 次点击  

如果我有三种硬币(一、二、五)。我有不同数量的硬币。我怎样才能使所有的组合都等于某个目标?

例如:

one = [1, 1, 1]  # 3 coins of 1
two = [2, 2]     # 2 coins of 2
five = [5, 5, 5] # 3 coins of 5
target = 10

使用此代码:

s = set()
one = 3
two = 2
five = 5

for c in combinations_with_replacement((0,1,1,1,2,2,5,5,5), 8):
    if sum(c) == target:
        s.add(c)

for c in s:
  if c.count(1) <= one and c.count(2) <= two and c.count(5) <= five:
    print(f"{c.count(1)} * one + {c.count(2)} * two + {c.count(5)}* five = 10")

给出了这些组合和目标的总和:

3 * one + 1 * two + 1 * five = 10
0 * one + 0 * two + 2 * five = 10
1 * one + 2 * two + 1 * five = 10

然而,我觉得这不是最好的方法,如何以更优雅的方式解决这个问题? 问题是如何使用 itertools , collections ,或其他模块来简化该任务。

没有嵌套 for 循环。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128952
 
1418 次点击  
文章 [ 2 ]  |  最新文章 3 年前