在python中,我有一个int并想从lis中减去它

2024-06-26 17:59:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在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除以50。
我需要在代码中更改什么? 谢谢!你知道吗


Tags: 用户in密码列表forinputifcash
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

好吧,我假设您正在尝试使用多种类型的票据来计算交易的变化。你知道吗

问题是,你需要保持一个连续的记录有多少变化,你还剩支付。我用num_curr_bill来计算您当前支付的账单类型有多少,而您的hef我改成了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:我会考虑去掉硬币纸币中的0.5,用1.0代替1,因为任何零碎的金额最终都是0.5的零碎。你知道吗

相关问题 更多 >