题解 | #自动售货系统#
自动售货系统
https://www.nowcoder.com/practice/cd82dc8a4727404ca5d32fcb487c50bf
class Goods:#商品
def __init__(self, amount):
a = [["A1", 0], ["A2", 0], ["A3", 0], ["A4", 0], ["A5", 0], ["A6", 0]]
self.price = {"A1": 2, "A2": 3, "A3": 4, "A4": 5, "A5": 8, "A6": 6}
for i in range(len(amount)):
a[i][1] = amount[i]
self.amount = dict(sorted(a, key=lambda x: x[1]))
class Depositbox:#存钱箱,余额
def __init__(self, amount):
b = [[1, 0], [2, 0], [5, 0], [10, 0]]
for i in range(len(amount)):
b[i][1] = amount[i]
self.thing = dict(b)
self.total = 0
def balance(self, post):
self.total += post
class Function:#功能
def p(self, money):#投币
small_value = depositbox.thing[1] + depositbox.thing[2] * 2
if money not in [1, 2, 5, 10]:
print("E002:Denomination error")
elif money in [5, 10] and money > small_value:
print("E003:Change is not enough, pay fail")
elif sum(goods.amount.values()) == 0:
print("E005:All the goods sold out")
else:
depositbox.thing[money] += 1
depositbox.balance(money)
print(f"S002:Pay success,balance={depositbox.total}")
def b(self, name):#买
if name not in ["A1", "A2", "A3", "A4", "A5", "A6"]:
print("E006:Goods does not exist")
elif goods.amount[name] == 0:
print("E007:The goods sold out")
elif depositbox.total < goods.price[name]:
print("E008:Lack of balance")
else:
depositbox.balance(goods.price[name] * (-1))
goods.amount[name] -= 1
print(f"S003:Buy success,balance={depositbox.total}")
def c1(self, cost):
x = cost
y = []
z = {1: 0, 2: 0, 5: 0, 10: 0}
for i, j in depositbox.thing.items():
for k in range(j):
y.append(i)
y.reverse()
for i in y:
if x == 0:
return z
if x - i >= 0:
z[i] += 1
x -= i
if x - i < 0:
continue
return False
def c(self):#退币
if depositbox.total == 0:
print("E009:Work failure")
elif depositbox.total > 0:
for q in range(depositbox.total, -1, -1):
if self.c1(q):
for i, j in self.c1(q).items():
depositbox.thing[i] -= j
depositbox.balance(i * j * (-1))
print(f"{i} yuan coin number={j}")
break
else:
return "ERROR"
def q(self, parameter):#查询
if parameter == 0:
amount = sorted(
list(goods.amount.items()), key=lambda x: x[1], reverse=True
)
for i in range(len(goods.price)):
print(amount[i][0], goods.price[amount[i][0]], amount[i][1])
elif parameter == 1:
for i, j in depositbox.thing.items():
print(f"{i} yuan coin number={j}")
order = input().split(";")
for i in order:
if "r" in i:
v = i.split()
n1 = list(map(int, v[1].split("-")))
n2 = list(map(int, v[2].split("-")))
goods = Goods(n1)
depositbox = Depositbox(n2)
print("S001:Initialization is successful")
function = Function()
if "p" in i:
v1 = int(i.split()[1])
function.p(v1)
if "b" in i:
v2 = i.split()[1]
function = Function()
function.b(v2)
if "c" in i:
function.c()
if "q" in i:
if i in ["q 0", "q 1"]:
v3 = int(i.split()[1])
function.q(v3)
else:
print("E010:Parameter error")
