首页 > 试题广场 >

自动售货系统

[编程题]自动售货系统
  • 热度指数:32239 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
1 总体说明
考生需要模拟实现一个简单的自动售货系统,实现投币、购买商品、退币、查询库存商品及存钱盒信息的功能。
系统初始化时自动售货机中商品为6种商品,商品的单价参见1.1规格说明,存钱盒内放置1元、2元、5元、10元钱币,商品数量和钱币张数通过初始化命令设置,参见2.1 系统初始化。
1.1规格说明
1. 商品:每种商品包含商品名称、单价、数量三种属性,其中商品名不重复。考生不能修改商品名称和单价,初始化命令设置商品数量。这些信息在考试框架中进行定义,考生在实现功能代码时可直接使用。
商品 名称
单价
数量
A1 2 X
A2 3 X
A3 4 X
A4 5 X
A5 8 X
A6 6 X
2. 存钱盒信息:钱币面额、张数两种属性。初始化命令设置各种面额钱币张数。这些信息在考试框架中进行定义,考生在实现功能代码时可直接使用。
钱币面额
张数
10元
X
5元
X
2元 X
1元 X
3. 退币原则
1) 根据系统存钱盒内钱币的 信息 ,按钱币总张数最少的原则进行退币。
2) 如果因零钱不足导致不能退币,则尽最大可能退币,以减少用户损失。
例如:假设存钱盒内只有4张2元,无其它面额钱币。如果需要退币7元,系统因零钱不足无法退币,则继续尝试退币6元,最终系统成功退币3张2元,用户损失1元钱币。
4. 投币操作说明:每次投币成功,投入的钱币面额累加到投币余额;同时,本次投入的钱币放入存钱盒中,存钱盒相应面额钱币增加。
5. 投币余额:指当前自动售货机中用户剩余的可购买商品的钱币总额;例如:投入2元面额的钱币,投币余额增加2元;购买一件价格2元的商品,投币余额减少2元;
6. 退币操作说明:退币操作需要遵守 退币原则 ;退币成功后,投币余额清零,同时扣除存钱盒相应的金额。
7. 购买商品操作说明:一次仅允许购买一件商品;购买商品成功后,自动售货机中对应商品数量减1,投币余额扣除本次购买商品的价格。
2 操作说明
命令字与第一个参数间使用一个空格分隔,多条命令采用分号隔开。考试系统会对输入命令格式进行处理,考生不需要关注输入命令格式的合法性,只需要实现命令处理函数。
2.1 系统初始化
命令格式
r A1 数量 -A2 数量 -A3 数量 -A4 数量 -A5 数量 -A6 数量 1 元张数 -2 元张数 -5 元张数 -10 元张数
参数名称
参数说明
类型
取值范围
A1数量
商品A1数量
整数
[0,30]
A2数量
商品A2数量
整数
[0,30]
A3数量
商品A3数量
整数
[0,30]
A4数量
商品A4数量
整数
[0,30]
A5数量
商品A5数量
整数
[0,30]
A6数量
商品A6数量
整数
[0,30]
1元张数
面额1元钱币张数
整数
[0,30]
2元张数
面额2元钱币张数
整数
[0,30]
5元张数
面额5元钱币张数
整数
[0,30]
10元张数
面额10元钱币张数
整数
[0,30]
商品和各种面额钱币取值范围只是作为初始化命令的限制,其它场景下不限制取值范围;考试框架已经实现取值范围的检查,考生不需要关注。
功能说明:设置自动售货机中商品数量和存钱盒各种面额的钱币张数;
约束说明:系统在任意阶段均可执行r初始化系统;考生不需要关注参数的合法性,不需要关注增加或缺少参数的场景;
输出说明:输出操作成功提示(执行完r命令后系统会自动输出操作结果,考生不需要再次调用输出函数),例:
命令 输出 含义
r 6-5-4-3-2-1 4-3-2-1; S001:Initialization is successful 初始化成功
2.2 投币
命令格式p 钱币面额
功能说明
(1) 如果投入非1元、2元、5元、10元的钱币面额(钱币面额不考虑负数、字符等非正整数的情况),输出“E002:Denomination error”;
(2) 如果存钱盒中1元和2元面额钱币总额小于本次投入的钱币面额,输出“E003:Change is not enough, pay fail”,但投入1元和2元面额钱币不受此限制。
(3) 如果自动售货机中商品全部销售完毕,投币失败。输出“E005:All the goods sold out”;
(4) 如果投币成功,输出“S002:Pay success,balance=X”;
约束说明
(1) 系统在任意阶段都可以投币;
(2) 一次投币只能投一张钱币;
(3) 同等条件下,错误码的优先级:E002 > E003 > E005;
输出说明:如果投币成功,输出“S002:Pay success,balance=X”。
例:
命令
输出
p 10;
S002:Pay success,balance=10
2.3 购买商品
命令格式b 商品名称
功能说明
(1) 如果购买的商品不在商品列表中,输出“E006:Goods does not exist”;
(2) 如果所购买的商品的数量为0,输出“E007:The goods sold out”;
(3) 如果投币余额小于待购买商品价格,输出“E008:Lack of balance”;
(4) 如果购买成功,输出“S003:Buy success,balance=X”;
约束说明
(1) 一次购买操作仅能购买一件商品,可以多次购买;
(2) 同等条件下,错误码的优先级:E006 > E007 > E008;
输出说明:
如果购买成功,输出“S003:Buy success,balance=X”。
例:
命令
输出
b A1;
S003:Buy success,balance=8
2.4 退币
命令格式c
功能说明
(1) 如果投币余额等于0的情况下,输出“E009:Work failure”;
(2) 如果投币余额大于0的情况下,按照 退币原则 进行“找零”,输出退币信息;
约束说明
(1) 系统在任意阶段都可以退币;
(2) 退币方式必须按照 退币原则 进行退币;
输出说明:如果退币成功,按照 退币原则 输出退币信息。
例,退5元钱币:
命令
输出
c;
1 yuan coin number=0
2 yuan coin number=0
5 yuan coin number=1
10 yuan coin number=0
2.5 查询
命令格式q 查询类别
功能说明
(1) 查询自动售货机中商品信息,包含商品名称、单价、数量。 根据商品数量从大到小进行排序;商品数量相同时,按照商品名称的先后顺序进行排序
例如:A1的商品名称先于A2的商品名称,A2的商品名称先于A3的商品名称。
(2) 查询存钱盒信息,包含各种面额钱币的张数;
(3) 查询类别如下表所示:
查询类别
查询内容
0
查询商品信息
1 查询存钱盒信息
如果“查询类别”参数错误,输出“E010:Parameter error”。“查询类别”参数错误时,不进行下面的处理;
输出说明
“查询类别”为0时,输出自动售货机中所有商品信息(商品名称单价数量)例:
命令
输出
q 0;
A1 2 6
A2 3 5
A3 4 4
A4 5 3
A5 8 2
A6 6 0
“查询类别”为1时,输出存钱盒信息(各种面额钱币的张数),格式固定。例:
命令
输出
q 1;
1 yuan coin number=4
2 yuan coin number=3
5 yuan coin number=2
10 yuan coin number=1


输入描述:

依照说明中的命令码格式输入命令。



输出描述:

输出执行结果

示例1

输入

r 22-18-21-21-7-20 3-23-10-6;c;q0;p 1;b A6;c;b A5;b A1;c;q1;p 5;

输出

S001:Initialization is successful
E009:Work failure
E010:Parameter error
S002:Pay success,balance=1
E008:Lack of balance
1 yuan coin number=1
2 yuan coin number=0
5 yuan coin number=0
10 yuan coin number=0
E008:Lack of balance
E008:Lack of balance
E009:Work failure
E010:Parameter error
S002:Pay success,balance=5
主要维护物品和钱币两个字典和一个剩余额度balance的全局变量,每个功能用一个函数实现即可,主要就是条件判断。
orders = input().split(';')
items = {'A1':[2, 0], 'A2':[3, 0], 'A3':[4, 0], 'A4':[5, 0], 'A5':[8, 0], 'A6':[6, 0]}
money_box = {10:0, 5:0, 2:0, 1:0}
balance = 0

def initialize(sum1:list, sum2:list):
    global balance
    # 两个参数分别表示物品的数量和钱币的数量
    for i in range(1,7):
        items['A'+str(i)][1] = sum1[i-1]
    money_box[1], money_box[2], money_box[5], money_box[10] = sum2
    return 'S001:Initialization is successful'

def insert(money:int):
    global balance
    if money not in [1, 2, 5, 10]:
        return 'E002:Denomination error'
    # 1,2无限制,只限制5和10
    if money_box[2] * 2 + money_box[1] * 1 < money and money in [5, 10]:
        return 'E003:Change is not enough, pay fail'
    num = 0
    for i in items.values():
        num += i[1]
    if num == 0:
        return 'E005:All the goods sold out'
    balance += money
    money_box[money] += 1
    return 'S002:Pay success,balance={}'.format(balance)

def buy(item:str):
    global balance
    if item in items.keys():
        if items[item][1] == 0:
            return 'E007:The goods sold out'
        else:
            if balance < items[item][0]:
                return 'E008:Lack of balance'
            else:
                balance -= items[item][0]
                return 'S003:Buy success,balance={}'.format(balance)
    else:
        return 'E006:Goods does not exist'

def refund():
    global balance
    if balance == 0:
        return 'E009:Work failure'
    else:
        money_list = {10:0, 5:0, 2:0, 1:0}
        # balance = 0或最小面值都大于balance
        while balance > 0:
            isrefund = False
            for i in [10, 5, 2, 1]:
                # 取最大的进行退款
                if i <= balance and money_box[i] >= 1:
                    isrefund =True
                    money_box[i] -= 1
                    balance -= i
                    money_list[i] += 1
                    break
            # 如果本轮未发生退款,跳出循环
            if not isrefund:
                break
        balance = 0
        return '1 yuan coin number={0}\n2 yuan coin number={1}\n5 yuan coin number={2}\n10 yuan coin number={3}'.format(money_list[1], money_list[2], money_list[5], money_list[10])

def lookup(kind:int):
    if kind == 0:
        items = sorted(items.items(), key=lambda x:x[1][1])
        info = ''
        for i in items.keys():
            info += i + str(items[i][0]) + ' ' + str(items[i][1]) + '\n'
        return info.strip() # 去掉结尾的换行符
    elif kind == 1:
        return '1 yuan coin number={0}\n2 yuan coin number={1}\n5 yuan coin number={2}\n10 yuan coin number={3}'.format(money_box[1], money_box[2], money_box[5], money_box[10])
    else:
        return 'E010:Parameter error'

for order in orders:
    # 主要是考虑到结尾可能出现空,索性提前判断一下
    if order:
        if order[0] == 'r':
            _, temp1, temp2 = order.split()
            print(initialize(list(map(int, temp1.split('-'))), list(map(int, temp2.split('-')))))
        elif order[0] == 'p':
            _, temp1= order.split()
            print(insert(int(temp1)))
        elif  order[0] == 'b':
            _, temp1= order.split()
            print(buy(temp1))
        elif  order[0] == 'c':
            print(refund())
        elif order[0] == 'q':
            if len(order.split()) == 2:
                print(lookup(int(order[2])))
            else:
                print('E010:Parameter error')


发表于 2023-04-16 09:21:40 回复(0)
_inputs = input().split(';')

#字典取数太麻烦了,换list
_ivt = [0] * 10

_dicg = {
    'A1':0,
    'A2':1,
    'A3':2,
    'A4':3,
    'A5':4,
    'A6':5
}

_dicm = {
    '1':6,
    '2':7,
    '5':8,
    '10':9
}

_price = {
    'A1':2,
    'A2':3,
    'A3':4,
    'A4':5,
    'A5':8,
    'A6':6
}


def _init(_cmd):
    # 初始化,命令格式r 22-18-21-21-7-20 3-23-10-6
    A, M = _cmd[2:].split()
    _i = 0
    for i in A.split('-'):
        _ivt[_i] = int(i)
        _i += 1
    for i in M.split('-'):
        _ivt[_i] = int(i)
        _i += 1
    print('S001:Initialization is successful')

_payc = 0

def _pay(_cmd):
    # 投币,命令格式p 10
    global _payc
    if _cmd[2:] not in ['1', '2', '5', '10']:
        # 投入钱币面值不对的话
        print('E002:Denomination error')
        return 0
    if _ivt[6] + _ivt[7] * 2 < int(_cmd[2:]) and _cmd[2:] not in ['1', '2']:
        # 如果存钱盒中1元和2元面额钱币总额小于本次投入的钱币面额
        # 但投入1元和2元面额钱币不受此限制
        print('E003:Change is not enough, pay fail')
        return 0
    if _ivt[:6].count(0) == 4:
        #  如果自动售货机中商品全部销售完毕
        print('E005:All the goods sold out')
        return 0
    _payc += int(_cmd[2:])
    if _cmd[2:] == '1':
        _ivt[6] += 1
    elif _cmd[2:] == '2':
        _ivt[7] += 1
    elif _cmd[2:] == '5':
        _ivt[8] += 1
    elif _cmd[2:] == '10':
        _ivt[9] += 1
    print('S002:Pay success,balance=%s' %_payc)
    return 1

def _buy(_cmd):
    # 购物,命令格式b A1
    goods = _cmd[2:]
    global _payc
    if goods not in _dicg:
        print('E006:Goods does not exist')
        return 0
    if _ivt[_dicg[goods]] == 0:
        print('E007:The goods sold out')
        return 0
    if _payc < _price[goods]:
        print('E008:Lack of balance')
        return 0
    _payc -= _price[goods]
    _ivt[_dicg[goods]] -= 1
    print('S003:Buy success,balance=%d' %_payc)

def _chg(_cmd):
    # 退币,命令格式c
    global _payc
    if _payc == 0:
        print('E009:Work failure')
        return 0
    if _payc > 0:
        # 退币原则,待写
        c1, c2, c5, c10 = 0,0,0,0
        while _payc > 0 :
            if _payc >= 10 and _ivt[9] >= 1:
                _payc -= 10
                _ivt[9] -= 1
                c10 += 1
            elif _payc >= 5 and _ivt[8] >= 1:
                _payc -= 5
                _ivt[8] -= 1
                c5 += 1
            elif _payc >= 2 and _ivt[7] >= 1:
                _payc -= 2
                _ivt[7] -= 1
                c2 += 1
            elif _payc >= 1 and _ivt[6] >= 1:
                _payc -= 1
                _ivt[6] -= 1
                c1 += 1
            else:
                _payc -= 1
        print('1 yuan coin number=%d' %c1)
        print('2 yuan coin number=%d' %c2)
        print('5 yuan coin number=%d' %c5)
        print('10 yuan coin number=%d' %c10)

def _query(_cmd):
    # 查询,命令格式q 0
    if _cmd[2:] == '0':
        # 查询商品信息
        # 排序
        _g = {i:_ivt[_dicg[i]] for i in _dicg}  # 商品列表
        _s = sorted(_g.items(), key = lambda _s:_s[1], reverse=True)    # 排序
        for i in _s:
            print(i[0], _price[i[0]], i[1])
    elif _cmd[2:] == '1':
        # 查询存钱盒信息
        for i in _dicm:
            print(i, 'yuan coin number=%d' %_ivt[_dicm[i]])
    print('E010:Parameter error')


for i in _inputs[:-1]:
    if i[0] == 'r':
        _init(i)
    if i[0] == 'p':
        _pay(i)
    if i[0] == 'b':
        _buy(i)
    if i[0] == 'c':
        _chg(i)
    if i[0] == 'q':
        _query(i)

发表于 2023-03-04 14:57:04 回复(0)
dic_s = {"A1": 0, "A2": 0, "A3": 0, "A4": 0, "A5": 0, "A6": 0}
dic_p = {"A1": 2, "A2": 3, "A3": 4, "A4": 5, "A5": 8, "A6": 6}
dic_m = {1: 0, 2: 0, 5: 0, 10: 0}
cmd = input().split(";")
shop = list(map(int, cmd[0].split()[1].split("-")))
money = list(map(int, cmd[0].split()[2].split("-")))
dic_s["A1"], dic_s["A2"], dic_s["A3"], dic_s["A4"], dic_s["A5"], dic_s["A6"] = (
    shop[0],
    shop[1],
    shop[2],
    shop[3],
    shop[4],
    shop[5],
)
dic_m[1], dic_m[2], dic_m[5], dic_m[10] = money[0], money[1], money[2], money[3]
print("S001:Initialization is successful")
cmd = cmd[1:-1]
balance = 0
for i in cmd:
    if i[0] == "p":
        if i[2:] not in ("1", "2", "5", "10"):
            print("E002:Denomination error")
            continue
        if i[2:] in ("5", "10"):
            if dic_m[1] * 1 + dic_m[2] * 2 < int(i[2:]):
                print("E003:Change is not enough, pay fail")
                continue
        if dic_s.values() == [0, 0, 0, 0, 0, 0]:
            print("E005:All the goods sold out")
            continue
        else:
            dic_m[int(i[1:])] += 1
            balance += int(i[1:])
            print(f"S002:Pay success,balance={balance}")
    elif i[0] == "b":
        if i[2:] not in dic_s:
            print("E006:Goods does not exist")
            continue
        if dic_s[i[2:]] == 0:
            print("E007:The goods sold out")
            continue
        if balance < dic_p[i[2:]]:
            print("E008:Lack of balance")
            continue
        else:
            balance -= dic_p[i[2:]]
            print(f"S003:Buy success,balance={balance}")
    elif i == "c":
        if balance == 0:
            print("E009:Work failure")
            continue
        coin_1 = 0
        coin_2 = 0
        coin_5 = 0
        coin_10 = 0
        while balance > 0:
            if balance >= 10 and dic_m[10] > 0:
                balance -= 10
                dic_m[10] -= 1
                coin_10 += 1
            elif balance >= 5 and dic_m[5] > 0:
                balance -= 5
                dic_m[5] -= 1
                coin_5 += 1
            elif balance >= 2 and dic_m[2] > 0:
                balance -= 2
                dic_m[2] -= 1
                coin_2 += 1
            elif balance >= 1 and dic_m[1] > 0:
                balance -= 1
                dic_m[1] -= 1
                coin_1 += 1
        print("1 yuan coin number=" + str(coin_1))
        print("2 yuan coin number=" + str(coin_2))
        print("5 yuan coin number=" + str(coin_5))
        print("10 yuan coin number=" + str(coin_10))
    elif i[0] == "q":
        if i[1:] == " 0":
            for j in dic_s:
                print(j + " " + str(dic_p[j]) + " " + str(dic_s[j]))
        elif i[1:] == " 1":
            print("1 yuan coin number=" + str(dic_m[1]))
            print("2 yuan coin number=" + str(dic_m[2]))
            print("5 yuan coin number=" + str(dic_m[5]))
            print("10 yuan coin number=" + str(dic_m[10]))
        else:
            print("E010:Parameter error")

发表于 2022-12-20 18:04:05 回复(0)
退币原则我没看太懂,原谅我没文化,但是我还是做出来了,感谢上帝
cmds=input()[:-1].split(';')

# 0forA1 1forA2 2forA3 ... 5forA6
products_name=['A1','A2','A3','A4','A5','A6']
products_price=[2,3,4,5,8,6]
products_in_stock=[0,0,0,0,0,0]
# 0for1yuan 1for2yuan 2for5yuan 3for10yuan
changes_value=[1,2,5,10]
changes_in_stock=[0,0,0,0]
# balance for the cumstomer
balance=0

# initializing shit when cmd = r
for full_cmd in cmds:
    cmd_type = full_cmd[0]
    if cmd_type == 'r':        #初始化指令
        r_list=full_cmd.split(' ')
        products_in_stock=list(map(int,r_list[1].split('-')))
        changes_in_stock=list(map(int,r_list[2].split('-')))
        #S001    输出操作成功提示
        print('S001:Initialization is successful')
    if cmd_type == 'p':        #客户投钱
        p_list=full_cmd.split(' ')
        p_insert=int(p_list[1])
        #E002    如果投入非1元、2元、5元、10元的钱币面额(钱币面额不考虑负数、字符等非正整数的情况),输出“E002:Denomination error”;
        if p_insert not in changes_value: #E002
            print('E002:Denomination error')
            continue
        #E003    如果存钱盒中1元和2元面额钱币总额小于本次投入的钱币面额,输出“E003:Change is not enough, pay fail”,但投入1元和2元面额钱币不受此限制。
        E003_changes_stock_v1v2_total_value=changes_value[0]*changes_in_stock[0]+changes_value[1]*changes_in_stock[1]
        if E003_changes_stock_v1v2_total_value < p_insert:
            print('E003:Change is not enough, pay fail')
            continue
        #E005    如果自动售货机中商品全部销售完毕,投币失败。输出“E005:All the goods sold out”;
        E005_total_products_quantity=sum(products_in_stock)
        if E005_total_products_quantity==0:
            print('E005:All the goods sold out')
            continue
        #S002    如果投币成功,输出“S002:Pay success,balance=X”
        balance+=p_insert
        changes_in_stock[changes_value.index(p_insert)]+=1
        print('S002:Pay success,balance={}'.format(balance))
    if cmd_type == 'b':
        b_list=full_cmd.split(' ')
        b_product_name=b_list[1]
        
        #E006    如果购买的商品不在商品列表中,输出“E006:Goods does not exist”;
        E006_goodsExist=b_product_name in products_name
        if not E006_goodsExist:
            print('E006:Goods does not exist')
            continue
        
        product_index=products_name.index(b_product_name)
        #E007    如果所购买的商品的数量为0,输出“E007:The goods sold out”;
        E007_goodsSoldout=products_in_stock[product_index] == 0
        if E007_goodsSoldout:
            print('E007:The goods sold out')
            continue
        
        #E008    如果投币余额小于待购买商品价格,输出“E008:Lack of balance”;
        b_product_price=products_price[product_index]
        if balance < b_product_price:
            print('E008:Lack of balance')
            continue
        
        #S003    如果购买成功,输出“S003:Buy success,balance=X”
        products_in_stock[product_index]-=1
        balance-=b_product_price
        print('S003:Buy success,balance={}'.format(balance))
    if cmd_type=='c':
        #E009    如果投币余额等于0的情况下,输出“E009:Work failure”;
        if balance == 0:
            print('E009:Work failure')
            continue
        
        
        #如果投币余额大于0的情况下,按照 退币原则 进行“找零”,输出退币信息;
        coin_returned=[0,0,0,0]
        # footnote1
        while balance != 0:
            if balance >= 10 and changes_in_stock[3] > 0:
                balance -= 10
                changes_in_stock[3]-=1
                coin_returned[3]+=1
                continue
            elif balance >= 5 and changes_in_stock[2] > 0:
                balance -= 5
                changes_in_stock[2]-=1 
                coin_returned[2]+=1
                continue
            elif balance >= 2 and changes_in_stock[1] > 0:
                balance -= 2
                changes_in_stock[1]-=1
                coin_returned[1]+=1
                continue
            elif balance >= 1 and changes_in_stock[0] > 0:
                balance -= 1
                changes_in_stock[0]-=1
                coin_returned[0]+=1
                continue
            balance-=1
            
        for i in range(len(changes_value)):
            print('{} yuan coin number={}'.format(changes_value[i],coin_returned[i]))
        
    if cmd_type=='q':
        q_list=full_cmd.split(' ')
        if len(q_list)!=2: 
            print('E010:Parameter error')
            continue
        q_mode=int(q_list[1])
        if q_mode == 0: #“查询类别”为0时,输出自动售货机中所有商品信息(商品名称单价数量)
            for i in range(len(products_price)):
                print(products_name[i],products_price[i],products_in_stock[i])
            continue
        if q_mode == 1:
            for i in range(len(changes_value)):
                print('{} yuan coin number={}'.format(changes_value[i],changes_in_stock[i]))
            continue
        # if didt went into 'ifs' above:
        # E010
        print('E010:Parameter error')

        
        
        
        
        ''' footnote1
        while balance != 0:
            min_stock_list=[]
            for v in changes_in_stock:
                if v != 0:min_stock_list.append(v)
                else: min_stock_list.append(31)
            if balance >= 10:
                mini=min(min_stock_list)
                possiblechanges=1
            elif balance >=5:
                mini=min(min_stock_list[:3])
                possiblechanges=2
            elif balance >=2:
                mini=min(min_stock_list[:2])
                possiblechanges=3
            else:
                mini=min(min_stock_list[:1])
                possiblechanges=4
            mini_check=False
            for i in range(len(changes_in_stock)-possiblechanges,-1,-1):
                if changes_in_stock[i] == mini:
                    # balance >= changes
                    if balance >= changes_value[i]:
                        balance -= changes_value[i]
                        changes_in_stock[i]-=1
                        coin_returned[i]+=1
                        mini_check=True#如果最小数量的changes 面额小于balance
                        break
                    # balance < changes
                    elif balance < changes_value[i]:
                        continue
            if not mini_check:
                balance-=1
            '''


发表于 2022-07-05 12:44:21 回复(0)
goods = {
    'A1': {'name':'A1', 'price':2, 'count':0},
    'A2': {'name':'A2', 'price':3, 'count':0},
    'A3': {'name':'A3', 'price':4, 'count':0},
    'A4': {'name':'A4', 'price':5, 'count':0},
    'A5': {'name':'A5', 'price':8, 'count':0},
    'A6': {'name':'A6', 'price':6, 'count':0},
}

moneys ={
    0: {'name':1, 'count':0},
    1: {'name':2, 'count':0},
    2: {'name':5, 'count':0},
    3: {'name':10, 'count':0},
}
surplus = 0

def initial(info):
    """
        根据用户输入的命令初始化商品和面额钱币的数量
    """
    data = []
    li0 = info[0].split('-')
    li1 = info[1].split('-')
    for i in li0:
        data.append(int(i))
    for j,v in zip(data,goods):
        goods[v]['count'] = j
    data = []
    for k in li1:
        data.append(int(k))
    for m,n in zip(data,moneys):
        moneys[n]['count'] = m 
    print('S001:Initialization is successful')


def buyGoods(arges):   # arges商品名称
    """
        购买商品:
            1.商品在商品列表/商品不在商品列表(字典)
            2.商品数量为0/商品数量不为0
            3.投币余额<购买的商品/投币余额>购买的商品
    """
    global surplus     # surplus 投币余额
    ingoods = arges[0]
    if ingoods in goods.keys():
        if goods[ingoods]['count'] != 0:
            if surplus >= goods[ingoods]['price']:
                surplus = surplus - goods[ingoods]['price']
                goods[ingoods]['count'] = goods[ingoods]['count']-1
                print('S003:Buy success,balance=%s' % surplus)
            else:
                print('E008:Lack of balance')
        else:
            print('E007,The goods sold out')
    else:
        print('E006,Goods does not exsit')
        
        
def payCoin(info):
    """
        投币:
            1.投币面额值是否准确
            2.商品数量是否为0
    """
    global surplus
    inmoneys = int(info[0])
    surplus = inmoneys + int(surplus)
    if inmoneys in [1,2,5,10]:
        if inmoneys < (moneys[0]['count'] + moneys[1]['count']*2):
            # if surplus <= 10:
            for i in goods.values():
                if i['count'] != 0:
                    break
            else:
                print('E005:All the goods sold out')
            for i in moneys.values():
                if inmoneys == i['name']:
                    i['count'] += 1
            print('S002:Pay success,balance=%d' % surplus)
        else:
            print('E003:Change is not enough,pay fail')
    else:
        print('E002:Denomination error')
    
    
def returnCoin():
    """
        退币:
            1.退币原则
                1) 根据系统存钱盒内钱币的信息,按钱币总张数最少的原则进行退币。
                2) 如果因零钱不足导致不能退币,则尽最大可能退币,以减少用户损失。
            2.投币余额等于0/投币余额>0
    """
    global surplus
    # print(surplus)
    li = [3,2,1,0]
    num = []
    if surplus != 0:
        if surplus > 0:
            for i in li:
                if surplus >= moneys[i]['name']:
                    if int(surplus/moneys[i]['name'])<=moneys[i]['count']:
                        num.append(int(surplus/moneys[i]['name']))
                        # print('%d yuan coin number=%d' % (moneys[i]['name'], int(surplus/moneys[i]['name'])))
                        surplus = surplus - (int(surplus/moneys[i]['name'])*moneys[i]['name'])
                    else:
                        num.append(int(moneys[i]['count']))
                        # print('%d yuan coin number=%d' % (moneys[i]['name'],moneys[i]['count']))
                        surplus = surplus - (moneys[i]['name'] * moneys[i]['count'])
                        
                else:
                    num.append(0)
                    # print('%d yuan coin number=0' % (moneys[i]['name']))
            result = zip(reversed(li),reversed(num))
            for (a,b) in result:
                print('%d yuan coin number=%d' % (moneys[a]['name'], b))
    else:
        print('E009:Work failure')
    
    
def queryGoods(info):
    """
        查询:0:商品信息
            1:存钱盒信息
    """
    if info[0] == '0':
        li = sorted(goods.values(), key=lambda v: (v['count'], v['price']), reverse=True)
        for i in li:
            print(list(i.values()))
    elif info[0] == '1':
        for coin in moneys.values():
            print('%d yuan coin number = %d' % (coin['name'], coin['count']))
    else:
        print('E010:Parameter error')


while True:
    try:
        surplus = 0
        comList = input().split(';')
        # comList = command.split(';')
        comAlpha = ['r', 'b', 'p', 'c', 'q']
        for com in comList:
            com2 = com.split(' ')
            if com2[0] == 'r':
                initial(com2[1:])
            elif com2[0] == 'b':
                buyGoods(com2[1:])
            elif com2[0] == 'p':
                payCoin(com2[1:])
            elif com2[0] == 'c':
                returnCoin()
            elif com2[0] == 'q':
                queryGoods(com2[1:])
            elif com2[0]=='q0'&nbs***bsp;com2[0]=='q1':
                print('E010:Parameter error')
            else:
                break
        
    except:
        break
这是我的代码,有两条用例没通过,不知道是代码的问题,还是用例的问题,代码确实稍微有点缺陷(输入命令C后,没有更新moneys字典中的钱币数量,但是好像对输出结果没啥影响),有问题的用例如下:
用例:
r 6-2-28-19-15-10 7-26-24-7;q0;b A2;c;q0;b A4;q1;b A5;q0;b A2;b A6;c;b A5;q1;q0;p 5;p 10;p 2;c;q0;p 2;p 5;q1;q1;p 5;p 5;c;p 5;p 1;b A3;p 5;c;b A3;p 5;
(这条我实在找不出哪里的问题了)
预期输出:
S001:Initialization is successful
E010:Parameter error
E008:Lack of balance
E009:Work failure
E010:Parameter error
E008:Lack of balance
E010:Parameter error
E008:Lack of balance
E010:Parameter error
E008:Lack of balance
E008:Lack of balance
E009:Work failure
E008:Lack of balance
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=5
S002:Pay success,balance=15
S002:Pay success,balance=17
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=1
E010:Parameter error
S002:Pay success,balance=2
S002:Pay success,balance=7
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=12
S002:Pay success,balance=17
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=1
S002:Pay success,balance=5
S002:Pay success,balance=6
S003:Buy success,balance=2
S002:Pay success,balance=7
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=0
E008:Lack of balance
S002:Pay success,balance=5
实际输出:
S001:Initialization is successful
E010:Parameter error
E008:Lack of balance
E009:Work failure
E010:Parameter error
E008:Lack of balance
E010:Parameter error
E008:Lack of balance
E010:Parameter error
E008:Lack of balance
E008:Lack of balance
E009:Work failure
E008:Lack of balance
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=5
S002:Pay success,balance=15
S002:Pay success,balance=17
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=1
E010:Parameter error
S002:Pay success,balance=2
S002:Pay success,balance=7
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=12
S002:Pay success,balance=17
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=1
S002:Pay success,balance=5
S002:Pay success,balance=6
S003:Buy success,balance=2
S002:Pay success,balance=7
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=0
E008:Lack of balance
S002:Pay success,balance=5

用例:
r 26-3-26-2-14-10 2-1-15-18;p 5;c;c;p 2;c;b A4;c;q1;q0;p 2;b A4;p 5;q0;c;q0;q1;q0;c;c;p 10;p 1;q0;
(感觉这条用例的预期结果这里少了一个1,实际输出应该是S002:Pay success,balance=11
预期输出:
S001:Initialization is successful
E003:Change is not enough, pay fail
E009:Work failure
E009:Work failure
S002:Pay success,balance=2
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=0
10 yuan coin number=0
E008:Lack of balance
E009:Work failure
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=2
E008:Lack of balance
S002:Pay success,balance=7
E010:Parameter error
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=0
E010:Parameter error
E010:Parameter error
E010:Parameter error
E009:Work failure
E009:Work failure
E003:Change is not enough, pay fail
S002:Pay success,balance=1
E010:Parameter error
实际输出:
S001:Initialization is successful
E003:Change is not enough,pay fail
1 yuan coin number=0
2 yuan coin number=0
5 yuan coin number=1
10 yuan coin number=0
E009:Work failure
S002:Pay success,balance=2
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=0
10 yuan coin number=0
E008:Lack of balance
E009:Work failure
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=2
E008:Lack of balance
S002:Pay success,balance=7
E010:Parameter error
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=0
E010:Parameter error
E010:Parameter error
E010:Parameter error
E009:Work failure
E009:Work failure
E003:Change is not enough,pay fail
S002:Pay success,balance=11
E010:Parameter error

发表于 2021-09-11 18:03:22 回复(1)