题解 | #自动售货系统#
自动售货系统
https://www.nowcoder.com/practice/cd82dc8a4727404ca5d32fcb487c50bf
def showr(strr): psr = strr.split() for i, v in enumerate(psr[1].split("-")): shop_list[i][1][1] = int(v) for i, v in enumerate(psr[2].split("-")): cun_list[i][1][0] = int(v) print('S001:Initialization is successful') def showp(strp): global ye qian = int(strp.split()[1]) if qian not in (1,2,5,10): print('E002:Denomination error') elif qian not in (1,2) and cun_map[1][0]+2*cun_map[2][0]<qian: print('E003:Change is not enough, pay fail') elif all([i[1][1]==0 for i in shop_list]): print('E005:All the goods sold out') else: cun_map[qian][0]+=1 ye += qian print(f'S002:Pay success,balance={ye}') def showb(strb): global ye sp = strb.split()[1] if sp not in ([i[0] for i in shop_list]): print('E006:Goods does not exist') elif shop_map[sp][1]==0: print('E007:The goods sold out') elif ye < shop_map[sp][0]: print('E008:Lack of balance') else: ye -= shop_map[sp][0] print(f'S003:Buy success,balance={ye}') def showc(): global ye tui = [0,0,0,0] if ye == 0: print('E009:Work failure') else: for index,i in enumerate((10,5,2,1)): while ye >= i and cun_map[i][0]>0: ye -= i cun_map[i][0] -= 1 tui[index]+=1 for index,i in enumerate((1,2,5,10)): print(f'{i} yuan coin number={tui[-(index+1)]}') ye = 0 def showq(strq): try: lq = int(strq.split()[1]) if lq not in (0,1): print('E010:Parameter error') return except: print('E010:Parameter error') return if lq == 0: for s in sorted(shop_list,key=lambda x:(-x[1][1],x[0])): print(s[0],s[1][0],s[1][1]) elif lq == 1: for s in sorted(cun_list,key=lambda x:x[0]): print(f'{str(s[0])} yuan coin number={str(s[1][0])}') ps = input().split(";") shop_list = [ ["A1", [2, 0]], ["A2", [3, 0]], ["A3", [4, 0]], ["A4", [5, 0]], ["A5", [8, 0]], ["A6", [6, 0]] ] cun_list = [[1, [0]], [2, [0]], [5, [0]], [10, [0]]] shop_map = dict(shop_list) cun_map = dict(cun_list) ye = 0 for ml in ps[:-1]: if ml[0]=='r': showr(ml) elif ml[0]=='p': showp(ml) elif ml[0]=='b': showb(ml) elif ml[0]=='c': showc() elif ml[0]=='q': showq(ml)
机试库的最后一题,完结撒花!!!
这题倒不是很难,主要是比较繁琐,保持逻辑清楚,一点点测试就会很好做,像代码中这样将每个功能封装成函数同时一点点自己写用例进行测试是个不错的办法。
这题当中让我学到一点点骚操作,python的列表如果不使用深拷贝直接用=号给别人赋值,实际上给到别人的是一个地址,对两个对象的改动会作用到同一个列表,这个平时不注意的时候非常坑,不容易报错也不容易排查,但是在这道题中,可以通过将字典的value注册成列表,此时对列表对象的所有更改都会同步到字典当中,这也是为什么代码中的钱币数量只有一个对象依然注册为了列表。这样在功能实现的过程中,需要遍历就使用列表,需要查询就使用字典,十分的方便。
还有一个小知识点,只要不在函数中注册同名局部变量,函数可以不通过global关键字直接访问到外面的列表以及字典全局对象,同时能够对列表的元素进行修改。
例如 a= [1,2,3] ,如果在函数中写 a=.... 这个操作是在函数中注册了一个a的局部变量,对外部的a列表不会有任何影响,但是a[0]=1,由于函数内没有名为a 的对象,函数会直接在外部找到a列表作为全局变量使用,不报错同时能对a列表进行全局的修改