|
| 1 | +"""Functions to keep track and alter inventory.""" |
| 2 | + |
| 3 | + |
| 4 | +def create_inventory(items: list) -> dict: |
| 5 | + """ |
| 6 | + Create a dict that tracks the amount (count) of each element |
| 7 | + on the `items` list. |
| 8 | +
|
| 9 | + :param items: list - list of items to create an inventory from. |
| 10 | + :return: dict - the inventory dictionary. |
| 11 | + """ |
| 12 | + inventory: dict = {} |
| 13 | + for item in items: |
| 14 | + inventory[item] = items.count(item) |
| 15 | + return inventory |
| 16 | + |
| 17 | + |
| 18 | +def add_items(inventory: dict, items: list) -> dict: |
| 19 | + """ |
| 20 | + Add or increment items in inventory using elements from the items `list`. |
| 21 | +
|
| 22 | + :param inventory: dict - dictionary of existing inventory. |
| 23 | + :param items: list - list of items to update the inventory with. |
| 24 | + :return: dict - the inventory updated with the new items. |
| 25 | + """ |
| 26 | + for item in set(items): |
| 27 | + count: int = items.count(item) |
| 28 | + if item in inventory: |
| 29 | + inventory[item] += count |
| 30 | + else: |
| 31 | + inventory[item] = count |
| 32 | + return inventory |
| 33 | + |
| 34 | + |
| 35 | +def decrement_items(inventory: dict, items: list) -> dict: |
| 36 | + """ |
| 37 | + Decrement items in inventory using elements from the `items` list. |
| 38 | +
|
| 39 | + :param inventory: dict - inventory dictionary. |
| 40 | + :param items: list - list of items to decrement from the inventory. |
| 41 | + :return: dict - updated inventory with items decremented. |
| 42 | + """ |
| 43 | + for item in set(items): |
| 44 | + if item in inventory: |
| 45 | + quantity: int = items.count(item) |
| 46 | + if inventory[item] >= quantity: |
| 47 | + inventory[item] -= quantity |
| 48 | + else: |
| 49 | + inventory[item] = 0 |
| 50 | + return inventory |
| 51 | + |
| 52 | + |
| 53 | +def remove_item(inventory: dict, item: str) -> dict: |
| 54 | + """ |
| 55 | + Remove item from inventory if it matches `item` string. |
| 56 | +
|
| 57 | + :param inventory: dict - inventory dictionary. |
| 58 | + :param item: str - item to remove from the inventory. |
| 59 | + :return: dict - updated inventory with item removed. |
| 60 | + Current inventory if item does not match. |
| 61 | + """ |
| 62 | + if item in inventory: |
| 63 | + inventory.pop(item) |
| 64 | + return inventory |
| 65 | + |
| 66 | + |
| 67 | +def list_inventory(inventory: dict) -> list: |
| 68 | + """ |
| 69 | + Create a list containing only available |
| 70 | + (item_name, item_count > 0) pairs in inventory. |
| 71 | +
|
| 72 | + :param inventory: dict - an inventory dictionary. |
| 73 | + :return: list of tuples - list of key, value pairs from the |
| 74 | + inventory dictionary. |
| 75 | + """ |
| 76 | + return [(key, inventory[key]) for key in inventory if inventory[key] != 0] |
0 commit comments