题解 | #自动售货系统# 完美解答

自动售货系统

https://www.nowcoder.com/practice/cd82dc8a4727404ca5d32fcb487c50bf

遇到这种题优先定义变量,类似于建立数据库

name = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']
nameK = {'A1': 0, 'A2': 1, 'A3': 2, 'A4': 3, 'A5': 4, 'A6': 5}
price = [2, 3, 4, 5, 8, 6]
count = [0] * 6

money = [1, 2, 5, 10]
moneyK = {1: 0, 2: 1, 5: 2, 10: 3}
moneyC = [0] * 4

# 可用余额
amount = 0


# 初始化
def r(sl):
    global count, moneyC

    count = list(map(int,sl[0].split('-')))
    moneyC = list(map(int,sl[1].split('-')))

    print('S001:Initialization is successful')


# 投币
def p(sl):
    global amount, moneyC
    a = int(sl[0])

    if a not in money:
        print('E002:Denomination error')
        return

    if a not in money[:2] and money[0] * moneyC[0] + money[1] * moneyC[1] < a:
        print('E003:Change is not enough, pay fail')
        return

    if sum(count) == 0:
        print('E005:All the goods sold out')
        return

    amount += a
    moneyC[moneyK[a]] += 1

    print(f'S002:Pay success,balance={amount}')
    return


# 购买商品
def b(sl):
    global amount, count

    if sl[0] not in name:
        print('E006:Goods does not exist')
        return

    i = nameK[sl[0]]

    if count[i] == 0:
        print('E007:The goods sold out')
        return

    if amount < price[i]:
        print('E008:Lack of balance')
        return

    amount -= price[i]
    count[i] -= 1

    print(f'S003:Buy success,balance={amount}')
    return


# 退币
def c(sl):
    global amount, moneyC
    if amount == 0:
        print('E009:Work failure')
        return

    back = [0] * len(money)
    i = 3
    while i >= 0 and amount > 0:
        if money[i] > amount or moneyC[i] == 0:
            i -= 1
            continue

        amount -= money[i]
        moneyC[i] -= 1
        back[i] += 1

    if sum(back) ==0:
        print('E009:Work failure')
        return

    for j in range(len(money)):
        print(f'{money[j]} yuan coin number={back[j]}')

    return


# 查询
def q(sl):

    if len(sl) < 1 or sl[0] not in ['0', '1']:
        print('E010:Parameter error')
        return

    if sl[0] == '0':
        c = list(enumerate(count))[::-1]
        c_sort = sorted(c, key=lambda x: x[1], reverse=True)
        for i, j in c_sort:
            print(f'{name[i]} {price[i]} {count[i]}')

    else:
        for i in range(len(money)):
            print(f'{money[i]} yuan coin number={moneyC[i]}')
        return


try:
    while True:
        st = [s.split() for s in input().split(';') if s]

        for s in st:
            if len(s) > 0 and s[0] in globals():
                globals()[s[0]](s[1:])
            else:
                print('E010:Parameter error')

except:
    pass

全部评论

相关推荐

牛客963010790号:为什么还要收藏
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务