尝试在Python中进行银行提款模拟器时出错

问题描述 投票:0回答:1

我是Python的新手,我正在尝试制作一个根据用户输入从银行提取资金的程序。只能使用$ 100,$ 50和$ 20的钞票。如果我输入60、80、110和其他值,则程序会使用最高的可用帐单,而剩下的提款金额则是银行无法提取的...

这里是代码:

 while True:
    try:
        money_amount = int(input('How much you want to withdraw? '))
        if money_amount == 0:
            print('Type in a valid value.')
            continue
    except ValueError:
        print('Not accepted. Try again.')
    else:
        print(f'Withdraw amount: $ {money_amount:.2f}')
        for bill_value in [100, 50, 20]:
            bill_quantity = money_amount // bill_value  # Divide saque // valor p/ encontrar quantia de cédulas
            money_amount %= bill_value  # Pega o resto da divisão de saque / valor. O que sobrar é calculado no próximo loop
            print(f'$ {bill_value} Bills → {bill_quantity}')

        if money_amount != 0:
            print(f'\033[31mERROR!\033[m This bank uses only \033[33m $ 100, $ 50 and $ 20 bills!!!\033[m')
            print('Try again.')
            continue
        break
print('\033[32mOperation Success\033[m')

如果我将值$ 1添加到Item列表中,则操作永远不会失败...[100,50,20,1]-可行,但这不是解决方案...如果有人可以帮助我理解为什么会发生这种情况以及我在做什么错,我将不胜感激。

python
1个回答
0
投票

您的提款逻辑有一个基本缺陷-您从最大到最小的贬义。这不适用于您所允许的有限账单。

您只能将钱兑换成现金

  • 本身除以20,就没有余数
  • 或当减去50(且不为负)除以20时没有余数
  • 100只不过是处理5个二十岁的奇特方式

任何其他输入都无法更改。您可以进行相应的编码:

def canBeChanged(x):
    return (x/20.0 == x//20.0) or x>=50 and ((x-50)/20.0 == (x-50)//20.0)


money = [1000, 110, 80, 60, 50, 20, 73, 10]

for m in money: 
    tmp = m
    if canBeChanged(m):
        change = []
        isDiv20 = (tmp/20.0 == tmp//20.0)  # divides by 20 without remainder
        if not isDiv20:
            change.append(50)              # remove 50, now it divides
            tmp -= 50

        twenties = tmp // 20       # how many 20's left?
        while twenties >=5:        # how many 100 bills can we combine from 5 20's?
            change.append(100)
            twenties -= 5
        while twenties:            # how many 20's left?
            change.append(20)
            twenties -= 1

        print(m, " == ", sorted(change))
    else:
        print(m, "can not be changed")

输出:

1000  ==  [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
110  ==  [20, 20, 20, 50]
80  ==  [20, 20, 20, 20]
60  ==  [20, 20, 20]
50  ==  [50]
20  ==  [20]
73 can not be changed
10 can not be changed
© www.soinside.com 2019 - 2024. All rights reserved.