查找25枚和50枚比萨硬币的所有可能组合,总计增加5卢比的零钱

时间:2019-01-30 04:26:19

标签: python itertools

我需要找到一种蟒蛇般的方法来找到25枚和50枚比萨硬币的所有组合,这些硬币的零钱总和为5卢比。

我是python的新手,想知道itertools.combination或itertools.permutaion是否可以帮助我找到该值。

Expected output
Combination #1: 25 Paisa x 0 + 50 Paisa x 10 = 5 Rs.
Combination #1: 25 Paisa x 2 + 50 Paisa x 9  = 5 Rs.
Combination #1: 25 Paisa x 4 + 50 Paisa x 8  = 5 Rs.
Combination #1: 25 Paisa x 6 + 50 Paisa x 7  = 5 Rs.
Combination #1: 25 Paisa x 8 + 50 Paisa x 6  = 5 Rs.
Combination #1: 25 Paisa x 10 + 50 Paisa x 5 = 5 Rs.
Combination #1: 25 Paisa x 12 + 50 Paisa x 4 = 5 Rs.
Combination #1: 25 Paisa x 14 + 50 Paisa x 3 = 5 Rs.
Combination #1: 25 Paisa x 16 + 50 Paisa x 2 = 5 Rs.
Combination #1: 25 Paisa x 18 + 50 Paisa x 1 = 5 Rs.
Combination #1: 25 Paisa x 20 + 50 Paisa x 0 = 5 Rs.

2 个答案:

答案 0 :(得分:1)

这是一个简单的解决方案

error NU1605: Detected package downgrade: Microsoft.AspNetCore.Razor.Design from 2.2.0 to 2.1.2. Reference the package directly from the project to select a different version.

输出:

coins = []

num_of_coins_25_paisa = 500/25

for i in range(num_of_coins_25_paisa+1):
    sum_of_25_paisa = 25*i
    remaining_amount = 500 - sum_of_25_paisa

    if remaining_amount % 50 == 0:
        coins.append((i,remaining_amount/50))

i = 1
for group in coins:
    print "Combination #1 : 25 Paisa x {0} + 50 Paisa x {1}  = 5 Rs.".format(group[0],group[1])

答案 1 :(得分:0)

这里是查找任何给定硬币组合的总和的最佳解决方案。

def change(amount, coins_available, coins_so_far):
    if sum(coins_so_far) == amount:
            yield coins_so_far
    elif sum(coins_so_far) > amount:
            pass
    elif coins_available == []:
            pass
    else:
            for c in change(amount, coins_available[:], coins_so_far+[coins_available[0]]):
                    yield c
            for c in change(amount, coins_available[1:], coins_so_far):
                    yield c

amount = 500
coins = [5, 25]

solutions = [s for s in change(amount, coins, [])]
i = 1
for s in solutions:
    print str(i) + " : " + str(s)
    i += 1

print 'optimal solution:', min(solutions, key=len)