-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinventory.py
More file actions
88 lines (67 loc) · 2.57 KB
/
Copy pathinventory.py
File metadata and controls
88 lines (67 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from collections import defaultdict
'''
Created on May 15, 2021
@author: kalina
'''
class InvalidItemType(Exception):
pass
class OutOfStock(Exception):
pass
class ItemUnlocked(Exception):
pass
class Inventory:
ITEM_AMOUNT = 0
ITEM_LOCK_STATE = 1
ITEM_INVALID = 0
def default_val():
return 0
def __init__(self):
self.__inventory = defaultdict(Inventory.default_val)
def __change_item_state(self, item_type, state):
if self.__inventory[item_type] == Inventory.ITEM_INVALID:
raise InvalidItemType("Item not in inventory")
else:
self.__inventory[item_type][Inventory.ITEM_LOCK_STATE] = state
def lock(self, item_type):
self.__change_item_state(item_type, True)
def unlock(self, item_type):
self.__change_item_state(item_type, False)
def purchase(self, item_type):
if self.__inventory[item_type] == Inventory.ITEM_INVALID:
raise InvalidItemType("Item does not exist")
elif self.__inventory[item_type][Inventory.ITEM_LOCK_STATE] == False:
raise ItemUnlocked("Item unlocked")
elif self.__inventory[item_type][Inventory.ITEM_AMOUNT] < 1:
raise OutOfStock("Item currently out of stock")
else:
self.__inventory[item_type][Inventory.ITEM_AMOUNT] = self.__inventory[item_type][Inventory.ITEM_AMOUNT] - 1
return self.count_items_left(item_type)
def add_stock(self, item_type, item_num=1):
if self.__inventory[item_type] == Inventory.ITEM_INVALID:
self.__inventory[item_type] = [item_num, False]
else:
new_num = item_num + \
self.__inventory[item_type][Inventory.ITEM_AMOUNT]
isLocked = self.__inventory[item_type][Inventory.ITEM_LOCK_STATE]
self.__inventory[item_type] = [new_num, isLocked]
def count_items_left(self, item_type):
if self.__inventory[item_type] == Inventory.ITEM_INVALID:
return 0
else:
return self.__inventory[item_type][Inventory.ITEM_AMOUNT]
if __name__ == "__main__":
item_type = "phone"
inv = Inventory()
inv.add_stock(item_type, 2)
inv.lock(item_type)
try:
num_left = inv.purchase(item_type)
except InvalidItemType:
print("Sorry, we don't sell {}".format(item_type))
except OutOfStock:
print("Sorry, that item is currently out of stock")
else:
print("Purchase complete. There are ""{} {}s left".format(
inv.count_items_left(item_type), item_type))
finally:
inv.unlock(item_type)