系统实现 | HJ98 自动售货系统
class Good: def __init__(self, name, price, num=0) -> None: self.name = name self.price = price self.num = num class VendingM: def __init__(self) -> None: self.goods = {} self.change = {} self.bank = 0 # self.init_sys(s) def init_sys(self, s): try: goods, change = s.split(' ') # 初始化商品 goods = list(map(int, goods.split('-'))) prices = {'A1': 2, 'A2':3, 'A3':4, 'A4':5, 'A5':8, 'A6':6} for i in range(1, 7): name, price = f'A{i}', prices[f'A{i}'] self.goods[name] = Good(name, price) for i in range(1, len(goods)+1): self.goods[f'A{i}'].num += goods[i-1] # 初始化零钱数量 change = list(map(int, change.split('-'))) self.change = {'1': 0, '2': 0, '5':0, '10': 0} self.change['1'] = change[0] self.change['2'] = change[1] self.change['5'] = change[2] self.change['10'] = change[3] print('S001:Initialization is successful') except: print('Initialization failed') def call_back(self, ): if self.bank == 0: print("E009:Work failure") else: back_money = self.bank res = {} for m in sorted(list(map(int, self.change.keys())), reverse=True): res[m] = back_money // int(m) self.change[str(m)] -= back_money // int(m) back_money %= int(m) self.print_money(res) self.bank = 0 def query(self, arg): if str(arg) not in ['0', '1']: print('E010:Parameter error') elif str(arg) == '0': s1 = sorted(self.goods.items(), key=lambda x:x[0]) s2 = sorted(s1, key=lambda x:x[1].num, reverse=True) for name, good in s2: print(f'{name} {good.price} {good.num}') else: self.print_money(self.change) def pull_money(self, money): all_goods = len([good.num for good in self.goods.values()]) change = self.change['1'] + self.change['2']*2 if int(money) not in [1, 2, 5, 10]: print('E002:Denomination error') elif int(money) > 2 and change < int(money): print('E003:Change is not enough, pay fail') elif all_goods == 0: print('E005:All the goods sold out') else: self.bank += int(money) self.change[money] += 1 print(f'S002:Pay success,balance={self.bank}') def buy_good(self, name): if name not in self.goods: print('E006:Goods does not exist') elif self.goods[name].num == 0: print('E007:The goods sold out') elif self.bank < self.goods[name].price: print('E008:Lack of balance') else: self.bank -= self.goods[name].price self.goods[name].num -= 1 print(f'S003:Buy success,balance={self.bank}') def print_money(self, money): for m in [1, 2, 5, 10]: print(f'{m} yuan coin number={money[m]}') test = VendingM() while True: try: coms = input().split(';') for com in coms: if com[0] == 'r': test.init_sys(com[2:]) elif com[0] == 'c': test.call_back() elif com[0] == 'q': test.query(com[2:]) elif com[0] == 'p': test.pull_money(com.split(' ')[1]) elif com[0] == 'b': test.buy_good(com.split(' ')[1]) except: break
用时:2h
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107