-2

在python中:如何将用户从列表中接收到的int分割,而每次它在for循环中运行时,我需要在下一轮中分割我从前一轮收到的值?

这是我的代码:

a = input('price: ')
b = input('cash paid: ')
coin_bills = [100, 50, 20, 10, 5, 1, 0.5]
if b >= a:
    for i in coin_bills:
        hef = b - a
        print (hef / i), '*', i
else:
    print 'pay up!'

示例:a=370 b=500 ---> b-a=130
现在在循环中(当 i=100 时)我将收到 1,并且(当 i=50 时)我将收到 2 但我希望在第二轮(当 i=50 时)将 30 ( 130[=b-a]- 100[=answer of round 1*i]) 除以 50。
什么我需要更改代码吗?谢谢!

4

2 回答 2

2

您只需要从您返回的更改总量中减去您在每个步骤中返回的更改量。如果您将变量名称更改为有意义的名称,则更容易查看:

price= int(raw_input('price: ')) # Use int(raw_input()) for safety.
paid= int(raw_input('cash paid: '))
coin_bills=[100,50,20,10,5,1,0.5]
if paid >= price:
    change = paid - price
    for i in coin_bills:
        # Use // to force integer division - not needed in Py2, but good practice
        # This means you can't give change in a size less than the smallest coin!
        print (change // i),'*',i
        change -= (change // i) * i # Subtract what you returned from the total change.
else:
    print 'pay up!'

您还可以通过仅打印您实际返回的硬币/纸币来稍微清除输出。那么内部循环可能看起来像这样:

for i in coin_bills:
    coins_or_bills_returned = change // i
    if coins_or_bills_returned: # Only print if there's something worth saying.
        print coins_or_bills_returned,'*',i
        change -= coins_or_bills_returned * i
于 2013-09-05T17:43:06.137 回答
0

好的,我假设您正在尝试使用多种类型的账单来计算交易的零钱。

问题是,您需要不断记录您还剩下多少零钱要支付。我曾经num_curr_bill计算过您要支付多少当前账单类型,而您的hefI 更改为remaining_change(所以这对我来说意味着什么)以支付剩余的零钱。

a= input('price: ')
b= input('cash paid: ')
coin_bills=[100,50,20,10,5,1,0.5]

if b>=a:
    # Calculate total change to pay out, ONCE (so not in the loop)
    remaining_change = b-a

    for i in coin_bills:
        # Find the number of the current bill to pay out
        num_curr_bill = remaining_change/i

        # Subtract how much you paid out with the current bill from the remaining change
        remaining_change -= num_curr_bill * i

        # Print the result for the current bill.
        print num_curr_bill,'*',i
else:
    print 'pay up!'

因此,对于 120 的价格和支付的现金 175,输出为:

price: 120
cash paid: 175
0 * 100
1 * 50
0 * 20
0 * 10
1 * 5
0 * 1
0.0 * 0.5

一张 50 的钞票和一张 5 的钞票加起来是 55,这是正确的变化。

编辑:我会更加谨慎地处理我自己代码中的注释,但我在此处添加它们以进行解释,以便您可以更清楚地了解我的思考过程。

编辑 2:我会考虑删除 coin_bills 中的 0.5 并将 1 替换为 1.0,因为任何小数最终都会是 0.5 的小数。

于 2013-09-05T17:43:02.057 回答