-
Notifications
You must be signed in to change notification settings - Fork 0
/
dicts.py
59 lines (43 loc) · 2.13 KB
/
dicts.py
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
"""Functions to keep track and alter inventory."""
ItemsType = list[str, ...]
InventoryType = dict[str, int]
def create_inventory(items: ItemsType) -> InventoryType:
"""Create a dict that tracks the amount (count) of each element on the `items` list.
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""
return add_items({}, items)
def add_items(inventory: InventoryType, items: ItemsType) -> InventoryType:
"""Add or increment items in inventory using elements from the items `list`.
:param inventory: dict - dictionary of existing inventory.
:param items: list - list of items to update the inventory with.
:return: dict - the inventory updated with the new items.
"""
for item in items:
inventory[item] = inventory.get(item, 0) + 1
return inventory
def decrement_items(inventory: InventoryType, items: ItemsType) -> InventoryType:
"""Decrement items in inventory using elements from the `items` list.
:param inventory: dict - inventory dictionary.
:param items: list - list of items to decrement from the inventory.
:return: dict - updated inventory with items decremented.
"""
for item in items:
if inventory[item] > 0:
inventory[item] -= 1
return inventory
def remove_item(inventory: InventoryType, item: str) -> InventoryType:
"""Remove item from inventory if it matches `item` string.
:param inventory: dict - inventory dictionary.
:param item: str - item to remove from the inventory.
:return: dict - updated inventory with item removed. Current inventory if item does not match.
"""
updated_inventory = inventory.copy()
updated_inventory.pop(item, None)
return updated_inventory
def list_inventory(inventory: InventoryType) -> list[tuple[str, int], ...]:
"""Create a list containing all (item_name, item_count) pairs in inventory.
:param inventory: dict - an inventory dictionary.
:return: list of tuples - list of key, value pairs from the inventory dictionary.
"""
return [(item, value) for item, value in inventory.items() if value > 0]