题解 | #自动售货系统#
自动售货系统
https://www.nowcoder.com/practice/cd82dc8a4727404ca5d32fcb487c50bf
d_price={'A1':2,'A2':3,'A3':4,'A4':5,'A5':8,'A6':6} d_qty={'A1':0,'A2':0,'A3':0,'A4':0,'A5':0,'A6':0} box={10:0,5:0,2:0,1:0} balance=0 def return_money(balance): q10,q5,q2,q1=0,0,0,0 while balance>0: if balance>=10 and box[10]>=1: balance-=10 q10+=1 box[10]-=1 elif balance>=5 and box[5]>=1: balance-=5 q5+=1 box[5]-=1 elif balance>=2 and box[2]>=1: balance-=2 q2+=1 box[2]-=1 elif balance>=1 and box[1]>=1: balance-=1 q1+=1 box[1]-=1 else: balance=0 return balance,q10,q5,q2,q1 commands=input().strip(';').split(';') for command in commands: l=command.split() if l[0]=='r': d_qty['A1'],d_qty['A2'],d_qty['A3'],d_qty['A4'],d_qty['A5'],d_qty['A6']=map(int,l[1].split('-')) box[1],box[2],box[5],box[10]=map(int,l[2].split('-')) print('S001:Initialization is successful') elif l[0]=='p': if l[1] not in ['1','2','5','10']: print('E002:Denomination error') elif l[1] in ['5','10'] and box[1]+box[2]*2<int(l[1]): print('E003:Change is not enough, pay fail') elif sum([d_qty['A1'],d_qty['A2'],d_qty['A3'],d_qty['A4'],d_qty['A5'],d_qty['A6']])==0: print('E005:All the goods sold out') else: balance+=int(l[1]) box[int(l[1])]+=1 print(f'S002:Pay success,balance={balance}') elif l[0]=='b': if l[1] not in d_price: print('E006:Goods does not exist') elif d_qty[l[1]]==0: print('E007:The goods sold out') elif balance<d_price[l[1]]: print('E008:Lack of balance') else: balance-=d_price[l[1]] d_qty[l[1]]-=1 print(f'S003:Buy success,balance={balance}') elif l[0]=='c': if balance==0: print('E009:Work failure') else: balance,q10,q5,q2,q1=return_money(balance) print(f'1 yuan coin number={q1}') print(f'2 yuan coin number={q2}') print(f'5 yuan coin number={q5}') print(f'10 yuan coin number={q10}') elif l[0]=='q': if l[1] not in ['0','1']: print('E010:Parameter error') elif l[1]=='0': for k in sorted(d_qty,key=lambda k:1000-d_qty[k]): print(f'{k} {d_price[k]} {d_qty[k]}') elif l[1]=='1': print(f'1 yuan coin number={box[1]}') print(f'2 yuan coin number={box[2]}') print(f'5 yuan coin number={box[5]}') print(f'10 yuan coin number={box[10]}') else: print('E010:Parameter error') 查询商品信息时,记得按商品数量排序输出。