首页 > 试题广场 >

自动售货系统

[编程题]自动售货系统
  • 热度指数:32284 时间限制: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
**,这题有毒,描述不清晰前后矛盾,这测试用例又是什么鬼???
goods = ['A1','A2','A3','A4','A5','A6']   # 商品种类
goods_price = [2,3,4,5,8,6]    # 商品价格
goods_num = [0,0,0,0,0,0]      # 商品数量

money = [10,5,2,1]         # 投币面额
money_num = [0,0,0,0]      # 投币张数

balance = [0]  # 投币余额

# 商品数量,存钱盒钱币张数初始化
def init(init_command):
    goods_num[0],goods_num[1],goods_num[2],goods_num[3],goods_num[4],goods_num[5] = 0,0,0,0,0,0
    money_num[0],money_num[1],money_num[2],money_num[3] = 0,0,0,0
    balance[0] = 0
    init_command_1 = init_command.split(' ')
    init_command_goods = init_command_1[1].split('-')
    for i in range(len(init_command_goods)):
        goods_num[i] = int(init_command_goods[i])
    init_command_money = init_command_1[2].split('-')
    for i in range(len(init_command_money)):
        money_num[i] = int(init_command_money[-(i+1)])

#p 10;
# 投币
def pay(pay_command):
    pay_command_1 = (pay_command.split(' '))[-1]
    # 投币余额不能超过10元
    # if balance[0] + int(pay_command_1) <= 10:
    if pay_command_1 not in ['1','2','5','10']:
        print("E002:Denomination error")
    elif pay_command_1 in ['5','10'] and (money[-1]*money_num[-1] + money[-2]*money_num[-2]) < int(pay_command_1):
        print("E003:Change is not enough, pay fail")
    elif sum(goods_num) == 0:
        print("E005:All the goods sold out")
    else:
        # 投币成功后,对应存钱盒钱币面额加1
        index_1 = money.index(int(pay_command_1))
        money_num[index_1] = money_num[index_1] + 1
        balance[0] = balance[0] + int(pay_command_1)
        print("S002:Pay success,balance=%s"%balance[0])

# b A1;
# 购买商品
def buy(buy_command):
    buy_command_1 = buy_command.split(' ')
    goods_index = goods.index(buy_command_1[-1])
    if buy_command_1[-1] not in goods:
        print("E006:Goods does not exist")
    elif int(goods_num[goods_index]) == 0:
        print("E007:The goods sold out")
    elif balance[0] < int(goods_price[goods_index]):
        print("E008:Lack of balance")
    else:
        goods_num[goods_index] = goods_num[goods_index] - 1    # 购买商品成功后,对应商品数量减1
        balance[0] = balance[0] - int(goods_price[goods_index])   # 购买商品成功后的投币余额
        print("S003:Buy success,balance=%s"%balance[0])

# q 0;
# 查询
def query(query_command):
    query_command_1 = query_command.split(' ')
    if query_command_1[-1] is '0':
        for i in range(int(len(goods))):
            query_list = []
            query_list.append((goods[i],str(goods_price[i]),str(goods_num[i])))
            query_list_1 = sorted(query_list, key=lambda x:x[2], reverse=True)
            for i in query_list_1:
                print(' '.join(i))
    elif query_command_1[-1] is '1':
        for i in range(1,int(len(money))+1):
            print("%s yuan coin number=%s"%(money[-i],money_num[-i]))
    else:
        print("E010:Parameter error")

# c;
# 退币
count_money_num = []
count_money_num_1 = []

def refund():
    m_10 = money_num[0] # 存钱盒10元面额张数
    m_5 = money_num[1]  # 存钱盒5元面额张数
    m_2 = money_num[2]  # 存钱盒2元面额张数
    m_1 = money_num[3]  # 存钱盒1元面额张数
    m = balance[0]
    if balance[0] == 0:
        print("E009:Work failure")
    elif balance[0] != 0:
        # 按张数最少原则退币
        for h in range(m_10 + 1):
            for i in range(m_5 + 1):
                for j in range(m_2 + 1):
                    for k in range(m_1 + 1):
                        if 10*h + 5 * i + 2 * j + 1 * k == m:
                            count_money_num.append((h, i, j, k))
        if len(count_money_num) == 0:
            # 尽最大可能退币
            for i in range(m_5 + 1):
                for j in range(m_2 + 1):
                    for k in range(m_1 + 1):
                        if 5 * i + 2 * j + 1 * k < m:
                            count_money_num_1.append((i, j, k, 5 * i + 2 * j + 1 * k))
            list_2 = sorted(count_money_num_1, key=lambda x: x[3])
            # 排序后取最大值
            # 退币成功后,投币余额清零,同时扣除存钱盒相应金额
            money_num[1] = money_num[1] - list_2[-1][0]
            money_num[2] = money_num[2] - list_2[-1][1]
            money_num[3] = money_num[3] - list_2[-1][2]
            for i in range(1, len(money)):
                print("%s yuan coin number=%s" % (money[-i], list_2[-1][-(i + 1)]))
            print("10 yuan coin number=0")
            # 退币成功后,投币余额清零,同时扣除存钱盒相应金额
            balance[0] = 0
            count_money_num.clear()
            count_money_num_1.clear()
        else:
            # 按张数最少原则退币
            list_1 = sorted(count_money_num, key=lambda x:(x[0] + x[1] + x[2] + x[3]))
            # 排序后取最小值
            # 退币成功后,投币余额清零,同时扣除存钱盒相应金额
            money_num[0] = money_num[0] - list_1[0][0]
            money_num[1] = money_num[1] - list_1[0][1]
            money_num[2] = money_num[2] - list_1[0][2]
            money_num[3] = money_num[3] - list_1[0][3]
            for i in range(1, len(money)+1):
                print("%s yuan coin number=%s" % (money[-i], list_1[0][-i]))
            # 退币成功后,投币余额清零,同时扣除存钱盒相应金额
            balance[0] = 0
            count_money_num.clear()

while True:
    try:
        command = input().split(';')
        for i in command:
            if 'r' in i:
                init(i)
                print('S001:Initialization is successful')
            elif 'p' in i:
                pay(i)
            elif 'b' in i:
                buy(i)
            elif 'q' in i:
                query(i)
            elif 'c' in i:
                refund()
    except:
        break


发表于 2021-02-10 16:21:54 回复(0)
这个test case 有毒。。。
最后一个test case 的 结果的第24行估计是设置这个时候提前按了一个回车。。。
具体请看输出结果对比图。。。




!!!! nmd  最后那个 “r” 怎么去下一行了。。。。
只能等着他们把这个bug修好了再跑吧。。。

同时我也试了其他人给的答案,都没跑通,估计是他偷偷摸摸有把test case改了。。。

附赠一份我写的code
一个 class 直接建立一个对象
退钱的方程用了DP,实际上可以用贪心,不过差距不大啦

"""
Created on Tue Dec 22 07:53:19 2020

@author: legen
"""

class Machine(object):
    def __init__(self, arr):
        self.products = arr[0]
        self.changes = arr[1]
        self.price = [2,3,4,5,8,6]
        self.balance = 0
        print("S001:Initialization is successful")
    
    def insertMoney(self, coin):
        if coin not in [1,2,5,10]:
            print("E002:Denomination error")
            return
        if coin in [5, 10]:
            if self.changes[0] + self.changes[1]*2 < coin:
                print("E003:Change is not enough, pay fail")
                return
        if sum(self.products) == 0:
            print("E005:All the goods sold out")
            return
        h = {1:0, 2:1, 5:2, 10:3}
        self.changes[h[coin]] += 1
        self.balance += coin
        print("S002:Pay success,balance={}".format(self.balance))
        return
    
    def buy(self, item):
        h = {'A1':0, 'A2':1, 'A3':2, 'A4':3, 'A5':4, 'A6':5}
        if item not in h:
            print("E006:Goods does not exist")
            return
        if self.products[h[item]] == 0:
            print("E007:The goods sold out")
            return
        if self.price[h[item]] > self.balance:
            print("E008:Lack of balance")
            return
        self.products[h[item]] -= 1
        self.balance -= self.price[h[item]]
        print("S003:Buy success,balance={}".format(self.balance))
        return
    
    def popChange(self):
        if self.balance == 0:
            print("E009:Work failure")
            return
        self._combination()
        return
    
    def _combination(self):
        val = [1,2,5,10]
        f = [[None] * 4 for y in range(self.balance+1)]
        for i in range(self.balance+1):
            if i == 0:
                for j in range(4):
                    f[i][j] = 0
                continue
            for j in range(len(val)):
                if i >= val[j]:
                    if f[i-val[j]][j] + 1 <= self.changes[j]:
                        if f[i-val[j]][0] is not None:
                            prev = sum(f[i-val[j]])
                        else:
                            continue
                        if f[i][0] is None:
                            for k in range(4):
                                f[i][k] = f[i-val[j]][k]
                            f[i][j] += 1
                        else:
                            if sum(f[i]) > prev+1:
                                for k in range(4):
                                    f[i][k] = f[i-val[j]][k]
                                f[i][j] += 1
        for i in range(len(f)-1, -1, -1):
            if f[i][0] is not None:
                for j in range(4):
                    print("{} yuan coin number={}".format(val[j], f[i][j]))
                    self.changes[j] -= f[i][j]
                break
        self.balance = 0
        return
    
    def queryItem(self):
        name = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']
        arr = [list(x) for x in zip(name, self.price, self.products)]
        arr.sort(key=lambda x: -x[2])
        for ele in arr:
            print(" ".join([str(x) for x in ele]))
        return
    
    def queryChange(self):
        val = [1,2,5,10]
        for i in range(len(self.changes)):
            print("{} yuan coin number={}".format(val[i], self.changes[i]))
        return

def vendingMachineOperation(jobs):
    for job in jobs:
        if job[0] == 'r':
            M = Machine([list(map(int, ele.split('-'))) for ele in job[1:]])
        elif job[0] == 'p':
            M.insertMoney(int(job[-1]))
        elif job[0] == 'b':
            M.buy(job[-1])
        elif job[0] == 'c':
            M.popChange()
        elif job[0] == 'q':
            if job[1] == 0:
                M.queryItem()
            elif job[1] == 1:
                M.queryChange()
            else:
                print("E010:Parameter error")
        else:
            print("E010:Parameter error")
    return


while True:
    try:
        jobs = list(input().split(';'))[:-1]
        jobs = [list(x.split()) for x in jobs]
        vendingMachineOperation(jobs)
    except:
        break


编辑于 2020-12-22 22:23:09 回复(1)

我有点怀疑在线测试的正确性
自己在本地测试,用的用例和在线测试一样,没有错误。只是少了末尾那个莫名其妙的初始化。
下面是我的代码(python 3):

class Goods(object):
    """Goods Class"""
    def __init__(self, name = 'g', price = 0, count = 0):
        self.name = name
        self.price = price
        self.count = count
    def set_count(self, c):
        self.count = c
class Cash(object):
    """Cash Class"""
    def __init__(self, name = 'yuan', denomination = 0, count = 0):
        self.name = name
        self.denomination = denomination
        self.count = count
    def set_count(self, c):
        self.count = c
shelf = {'A1':2, 'A2':3, 'A3':4, 'A4':5, 'A5':8, 'A6':6}
bank = {'10 yuan':10, '5 yuan':5, '2 yuan':2, '1 yuan':1}
A1 = Goods(name = 'A1', price = shelf['A1'])
A2 = Goods(name = 'A2', price = shelf['A2'])
A3 = Goods(name = 'A3', price = shelf['A3'])
A4 = Goods(name = 'A4', price = shelf['A4'])
A5 = Goods(name = 'A5', price = shelf['A5'])
A6 = Goods(name = 'A6', price = shelf['A6'])

C_10 = Cash(name = '10 yuan coin', denomination = 10)
C_5 = Cash(name = '5 yuan coin', denomination = 5)
C_2 = Cash(name = '2 yuan coin', denomination = 2)
C_1 = Cash(name = '1 yuan coin', denomination = 1)


Initialization = False
p_pay = 0
balance = 0
while True:
    try:
        code = input().strip().split(';')

        if code[-1] == '':
            code.pop()
        for c in code:
            #initialization
            if c[0] == 'r':
                r_good = c.split(' ')[1].split('-')
                r_cash = c.split(' ')[2].split('-')

                A1.set_count(int(r_good[0]))
                A2.set_count(int(r_good[1]))
                A3.set_count(int(r_good[2]))
                A4.set_count(int(r_good[3]))        
                A5.set_count(int(r_good[4]))
                A6.set_count(int(r_good[5]))    

                C_10.set_count(int(r_cash[0]))
                C_5.set_count(int(r_cash[1]))
                C_2.set_count(int(r_cash[2]))
                C_1.set_count(int(r_cash[3]))

                print('S001:Initialization is successful')

            #pay
            elif c[0] == 'p':
                p_pay = int(c.split(' ')[1])
                if p_pay not in [1,2,5,10]:
                    print('E002:Denomination error')
                elif p_pay > 10:
                    print('E004:Pay the balance is beyond the scope biggest')
                elif (C_1.denomination*C_1.count + C_2.denomination*C_2.count) < p_pay:
                    if p_pay in [5,10]:
                        print('E003:Change is not enough, pay fail')
                    elif p_pay in [1,2]:
                        if (A1.count + A2.count + A3.count + A4.count + A5.count + A6.count) ==0:
                            print('E005:All the goods sold out')
                        else:
                            balance = balance + p_pay
                            locals()['C_' + str(p_pay)].set_count(locals()['C_' + str(p_pay)].count + 1)
                            print('S002:Pay success,balance=',balance)
                else:
                    if (A1.count + A2.count + A3.count + A4.count + A5.count + A6.count) >0:
                        balance = balance + p_pay
                        locals()['C_' + str(p_pay)].set_count(locals()['C_' + str(p_pay)].count + 1)
                        print('S002:Pay success,balance=',balance)

            #buy
            elif c[0] == 'b':
                b_buy = c.split(' ')[1]
                if b_buy not in shelf.keys():
                    print('E006:Goods does not exist')
                    #break
                elif locals()[b_buy].count == 0:
                    print('E007:The goods sold out')

                elif balance < locals()[b_buy].price:
                    print('E008:Lack of balance')

                else:

                    balance = balance - locals()[b_buy].price
                    locals()[b_buy].set_count(locals()[b_buy].count - 1)

                    print('S003:Buy success,balance=',balance)

            #c 退币
            elif c[0] == 'c':
                c_cell = []
                bank_denomination = sorted(bank.items(),key = lambda item:item[1], reverse = True)
                for k in range(len(bank_denomination)):
                    c_num =  balance//(bank_denomination[k][1])
                    balance = balance%(bank_denomination[k][1])
                    c_cell.append(c_num)
                for l in range(len(bank_denomination)):
                    #locals()['C_' + str(bank_denomination[-1 - l][1])].set_count(locals()['C_' + str(bank_denomination[-1 - l][1])].count - c_cell[-1 - l])
                    locals()['C_' + str(bank_denomination[-1 - l][1])].set_count(locals()['C_' + str(bank_denomination[-1 - l][1])].count - c_cell[-1 - l]) 
                    print(bank_denomination[-1 - l][0] + ' coin number=' + str(c_cell[-1 - l]))

                balance = 0
                p_pay = 0

            #query
            elif c[0] == 'q':

                if ' ' not in c:
                    print('E010:Parameter error')
                    #break
                else:
                    q_category = c.split(' ')[1]
                    if q_category not in ['0','1']:
                        print('E010:Parameter error')
                        #break   

                    elif q_category == '0':
                        for g in range(6):
                            g_name = 'A'+str(g+1)
                            print(locals()[g_name].name + ' ' + str(locals()[g_name].price) + ' ' + str(locals()[g_name].count))
                    elif q_category == '1':
                        for g in range(4):
                            g_name = 'C_' + str(sorted(bank.items(), key = lambda item:item[1])[g][1])
                            print(locals()[g_name].name + ' number=' + str(locals()[g_name].count))

    except:
        break
发表于 2020-07-16 19:45:08 回复(1)
class sell:
    
    def __init__(self):
        self.A = None
        self.N_A = None
        self.money = None
        self.balance = 0
        
    def dostring(self,s):
        s = s.split(";")
        self.init(s[0])
        for i in range(1,len(s)):
            if len(s[i])>0:
                if s[i][0]=="p":self.OpPay(s[i])
                if s[i][0]=='b':self.OpBuy(s[i])
                if s[i][0]=='c':self.OpChange()
                if s[i][0]=='q':self.OpQuary(s[i])
        return
    
    def init(self,a):
        a = a.replace("-"," ")
        a = a.split()
        for i in range(len(a)):
            if a[i]=='r':
                self.A = {'A1':[2,int(a[i+1])],'A2':[3,int(a[i+2])],'A3':[4,int(a[i+3])],'A4':[5,int(a[i+4])],'A5':[8,int(a[i+5])],'A6':[6,int(a[i+6])]}
                self.N_A = [int(a[i+j]) for j in range(1,7)]
        self.money = {1:int(a[7]),2:int(a[8]),5:int(a[9]),10:int(a[10])}
        print("S001:Initialization is successful")
    
    def OpPay(self,temp):
        temp2 = temp.split(" ")
        p = int(temp2[1])
        if p not in [1,2,5,10]:
            print("E002:Denomination error")
            return
        M = 1 * self.money[1] + 2 * self.money[2]
        if (M < p)&(p not in [1,2]):
            print("E003:Change is not enough, pay fail")
            return
        if p>10:
            print("E004:Pay the balance is beyond the scope biggest")
            return
        if sum(self.N_A)==0:
            print("E005:All the goods sold out")
            return
        else:
            self.money[p] = self.money[p]+1
            self.balance = self.balance + p
            print("S002:Pay success,balance="+str(self.balance))
    
    def OpBuy(self,temp):
        temp2 = temp.split(" ")
        b = temp2[1]
        if b not in self.A:
            print("E006:Goods does not exist")
            return
        if self.A[b][1] == 0:
            print("E007:The goods sold out")
            return 
        if self.balance < self.A[b][0]:
            print("E008:Lack of balance")
            return        
        self.balance = self.balance-self.A[b][0]
        print("S003:Buy success,balance="+str(self.balance))
    
    def OpChange(self):
        c = self.balance
        if c == 0:
            print("E009:Work failure",end='')
        else:
            T = [0,0,0,0]
            while c > 0:
                if (c >= 10) & (self.money[10]>0):
                    T[3] = T[3]+1
                    c = c - 10
                    self.money[10] = self.money[10] - 1
                elif (c >= 5) & (self.money[5]>0):
                    T[2] = T[2]+1
                    c = c - 5
                    self.money[5] = self.money[5] - 1
                elif (c >= 2) & (self.money[2]>0):
                    T[1] = T[1]+1
                    c = c - 2
                    self.money[2] = self.money[2] - 1
                elif c > self.money[1]:
                    T[0] = T[0]+self.money[1]
                    self.money[1] = 0
                    c = 0
                else:
                    T[0] = T[0]+c
                    self.money[1] = self.money[1]-c
                    c = c - 1
            print("1 yuan coin number="+str(T[0]))
            print("2 yuan coin number="+str(T[1]))
            print("5 yuan coin number="+str(T[2]))
            print("10 yuan coin number="+str(T[3]))
            self.balance = 0
        
    def OpQuary(self,temp):
        if temp == 'q 0':
            for v in self.A:
                print(v+str(self.A[v][0])+str(self.A[v][1]))
        if temp == 'q 1':
            print("1 yuan coin number="+str(self.money[1]))
            print("2 yuan coin number="+str(self.money[2]))
            print("5 yuan coin number="+str(self.money[5]))
            print("10 yuan coin number="+str(self.money[10]))
        else:
            print("E010:Parameter error",end='')

if __name__ == '__main__':
    while True:
        try:
            S = sell()
            a = input()
            S.dostring(a)
        except:break

发表于 2020-06-15 20:50:06 回复(2)
def sys_init(s):
    goods = [['A1',2],['A2,3'],['A3',4],['A4',5],['A5',8],['A6',6]]
    case = [[1],[2],[5],[10]]
    goods_init, case_init = s.split()[1].split("-"), s.split()[2].split("-")
    for i in range(6):
        goods[i].append(int(goods_init[i]))
    for i in range(4):
        case[i].append(int(case_init[i]))
    print("S001:Initialization is successful")
    return goods,case
        
def deliver(s):
    global rest, goods, case
    coin = int(s.split()[1])
    templist = [1,2,5,10]
    if coin in templist:
        case[templist.index(coin)][1] += 1
    rest += coin
    if coin not in [1,2,5,10]:
        print("E002:Denomination error")
    elif 1*case[0][1] + 2*case[1][1] < coin and coin not in [1,2]:
        print("E003:Change is not enough, pay fail")
    elif coin > 10:
        print("E004:Pay the balance is beyond the scope biggest")
    elif case[0][1] == 0 and case[1][1] == 0 and case[2][1] == 0 and case[3][1] == 0:
        print("E005:All the goods sold out")
    else:
        print("S002:Pay success,balance=%d" % rest)
        
def purchase(s):
    global rest, goods, case
    name = s.split()[1]
    if name not in ['A1','A2','A3','A4','A5','A6']:
        print("E006:Goods does not exist")
    elif goods[int(name[1])-1][2] == 0:
        print("E007:The goods sold out")
    elif rest < goods[int(name[1])-1][1]:
        print("E008:Lack of balance")
    else:
        rest -= goods[int(name[1])-1][1]
        goods[int(name[1])-1][2] -= 1
        print("S003:Buy success,balance=%d" % rest)
        
def back(s):
    global rest, goods, case
    backlist = []
    if rest == 0:
        print("E009:Work failure")
    else:
        for i in range(3,-1,-1):
            if rest//case[i][0] < case[i][1]:
                backlist.append(rest//case[i][0])
            else:
                backlist.append(case[i][1])
            rest = rest - backlist[3-i] * case[i][0]
    for i in range(4):
        print("%d yuan coin number=%d" % (case[i][0],backlist[3-i]))
        
def equiry(s):
    global goods, case
    if len(s.split()) == 2:
        ask = int(s.split()[1])
    else:
        ask = -1
    if ask == 0:
        templist = [goods[0][2],goods[1][2],goods[2][2],goods[3][2],\
                    goods[4][2],goods[5][2]]
        while len(templist) > 0:
            x = max(templist)
            while x in templist:
                templist.remove(x)
            for i in range(6):
                if goods[i][2] == x:
                    print(goods[i][0]," ",goods[i][1]," ",goods[i][2]," ")
    elif ask == 1:
        for i in range(4):
            print("%d yuan coin number=%d" % (case[i][0],case[i][1]))
    else:
        print("E010:Parameter error", end = "")
        
while True:
    try:
        order = input().split(";")
        order2 = input().split(";")
        rest = 0
        for i in range(len(order)):
            if order[i][0] == "r":
                goods, case = sys_init(order[i])
            elif order[i][0] == "p":
                deliver(order[i])
            elif order[i][0] == "b":
                purchase(order[i])
            elif order[i][0] == "c":
                back(order[i])
            elif order[i][0] == "q":
                equiry(order[i])
    except:
        break
大概这样写,不是很严谨完善,也没有通过下面的用例,不太清楚用例输入到底是怎样的会出现多一个初始化
用例:
r 25-9-1-1-12-20 7-3-8-14;p 10;p 10;b A3;c;b A1;q0;p 10;p 5;c;p 1;b A5;q0;

对应输出应该为:

S001:Initialization is successful
S002:Pay success,balance=10
S002:Pay success,balance=20
S003:Buy success,balance=16
1 yuan coin number=1
2 yuan coin number=0
5 yuan coin number=1
10 yuan coin number=1
E008:Lack of balance
E010:Parameter errorS002:Pay success,balance=10
S002:Pay success,balance=15
1 yuan coin number=0
2 yuan coin number=0
5 yuan coin number=1
10 yuan coin number=1
S002:Pay success,balance=1
E008:Lack of balance
E010:Parameter errorS001:Initialization is successful

发表于 2020-06-01 23:54:16 回复(3)