2012-01-25 169 views
2

我被要求用python编写一个程序,该程序能够正确地找到硬币的组合,以及每个硬币的数量。在这个问题中只使用了镍和硬币。确定python中的硬币组合

Ex - 考虑到有10个硬币,在$ .85中有多少个镍和硬币?

这是我如何解决它:

  1. 设置方程:

    d + N = 10
    .10d + .05n = 0.85

  2. 求解N:
    n = 10 - d

  3. 解决方案:
    .10d + 0.05(10-d)= 0.85
    .05d + 0.5 -.05d = 0.85
    .05d = 0.35
    d = 7
    n = 3的

我该如何编程呢?

对不起,如果这是一个愚蠢的问题,但我很新的python,我完全失去了这一个。

+1

您需要提供'some'代码。您将通过尝试了解更多。也许一个好的Python教程(谷歌潜入Python)可以提供帮助。 – ChristopheD

+0

你有任何编程经验吗? (任何语言) –

+0

* .05d + .5 -.05d = .85 * nope,无论d是什么,它总是0.5。 ;) – Gandaro

回答

2

对于风格没有要点,但是对于所有可能性的简单搜索很快就可以写出来,并且足够快以用于实际目的。从所有的镍币开始,不用硬币,然后继续添加一个硬币并从镍币中取出一个,直到你得到答案(或不)。

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! 
+0

你可以使用'filter'来做到这一点。例如:'filter(lambda x:x [0] * 5 + x [1] * 10 == 85,enumerate(range(11)[:: - 1]))'(虽然这只是更短)。 – Gandaro

5

让硬币数量是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) 
+0

最佳解决方案! :) – Gandaro

+0

+1使用代数将解决方案简化为快速计算,而不是循环结构。 – Makoto

1

如果你只有一角硬币和镍币,你可以做到以下几点:

>>> 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点五分,你可以计算出有多少镍币,并为每两个镍币加一个硬币,直到你拥有合适数量的硬币。

+0

如果OP正在阅读此内容,请输入'D K'的答案六次,或直到停止看起来像一个foriegn语言。 – Droogans

0

或者,而不是通过硬币可能连击迭代,你可以使用(给定的总和numcoins输入):

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

如果你得到负数的答案,那么具体的组合之一(如.85由5个硬币组成)无法解决。