簡體   English   中英

確定python中的硬幣組合

[英]Determining coin combinations in python

我被要求在python中編寫一個程序,能夠在給定的金額中正確地找到硬幣的組合和每個硬幣的數量。 在這個問題中,僅使用鎳和硬幣。

前 - 鑒於有10個硬幣,有多少鎳幣和硬幣在0.85美元?

這就是我解決它的方式:

  1. 方程式:

    d + n = 10
    .10d + .05n = .85

  2. 解決n:
    n = 10 - d

  3. 解決:
    .10d + .05(10-d)= .85
    .05d + .5 -.05d = .85
    .05d = .35
    d = 7
    n = 3

我該如何編程呢?

對不起,如果這是一個愚蠢的問題,但我是python的新手,我完全迷失在這一個。

設硬幣數為a ,所以d + n = a

設和為b ,所以0.1d + 0.05n = b

然后

n = a - d
0.1d+0.05(a-d)=b
0.05d = b-0.05a
d = 20b - a
n = a - d = a - 20b +a = 2a - 20b

所以,給出ab

d = 20b - a
n = a - d

現在我們只需要在Python中編寫這兩個公式。

請查看官方文檔中的示例: http//docs.python.org/tutorial/controlflow.html#defining-functions

def count(num, total_sum):
    d = 20*total_sum - num
    n = num - d
    return (n,d)

print count(10, 0.85)

沒有風格的要點,但是對所有可能性的簡單搜索可以快速編寫並且足夠快以用於實際目的。 從所有的鎳幣開始,沒有硬幣,然后繼續添加一個硬幣並從鎳中刪除一個,直到你得到答案(或不)。

def solve(ncoins, cents):
    nickels = ncoins
    dimes = 0
    for ii in range(ncoins):
        if (nickels * 5) + (dimes * 10) == cents:
            return "{nickels} nickels, {dimes} dimes".format(
                nickels=nickels, dimes=dimes)
        nickels -= 1
        dimes += 1
    raise AssertionError("{ncoins} coins can't be {cents} cents!".format(
        ncoins=ncoins, cents=cents))

print solve(10, 85)
print solve(10, 75)
print solve(100, 75)

輸出:

3 nickels, 7 dimes
5 nickels, 5 dimes
Traceback (most recent call last):
  File "/home/akg/tmp/sacoins.py", line 16, in <module>
    print solve(100, 75)
  File "/home/akg/tmp/sacoins.py", line 10, in solve
    raise AssertionError("{ncoins} coins can't be {cents} cents!".format(ncoins=ncoins, cents=cents))
AssertionError: 100 coins can't be 75 cents!

如果你只有硬幣和鎳幣,你可以做以下事情:

>>> total_coins = 10
>>> nickels = 85 / 5  # 85 is the total amount in cents; 5 is the value of a nickel
>>> nickels
17
>>> dimes = 0
>>> while dimes + nickels != total_coins:
...    dimes += 1
...    nickels -= 2
... 
>>> dimes
7
>>> nickels
3
>>>

由於每角錢有2個鎳幣,你可以計算出有多少鎳幣,並為每兩個鎳幣添加一個鎳幣,直到你擁有正確數量的硬幣。

或者不是迭代可能的硬幣組合,你可以使用(給定總和和numcoin作為輸入):

justnickels = total/.05 
numdimes = justnickels - numcoins
numnickels = numcoins - numdimes

如果你得到負數作為答案之一,那么特定的組合(如.85由5個硬幣組成)是無法解決的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM