Files
exercism_puzzles/python/mecha-munch-management/dict_methods.py
T

94 lines
3.1 KiB
Python

"""Functions to manage a users shopping cart items."""
from re import fullmatch
def add_item(current_cart, items_to_add):
"""Add items to shopping cart.
:param current_cart: dict - the current shopping cart.
:param items_to_add: iterable - items to add to the cart.
:return: dict - the updated user cart dictionary.
"""
# create a new cart with items_to_add if current_cart is empty
# if current_cart == {}:
# current_cart = dict.fromkeys(items_to_add, 0)
# for item in items_to_add:
# current_cart[item] += 1
# return current_cart
# (after doing this i realized that the bellow code also addresses the
# concern of the current_cart being empty, so i commented out the code
# above)
# increment item by one if item already exists in current_cart,
# otherwise add new item to current_cart with value of 1
for item in items_to_add:
current_cart[item] = current_cart.get(item, 0) + 1
return current_cart
def read_notes(notes):
"""Create user cart from an iterable notes entry.
:param notes: iterable of items to add to cart.
:return: dict - a user shopping cart dictionary.
"""
shopping_cart: dict = dict.fromkeys(notes, 0)
for item in notes:
shopping_cart[item] += 1
return shopping_cart
def update_recipes(ideas, recipe_updates):
"""Update the recipe ideas dictionary.
:param ideas: dict - The "recipe ideas" dict.
:param recipe_updates: dict - dictionary with updates for the ideas section.
:return: dict - updated "recipe ideas" dict.
"""
ideas |= recipe_updates
return ideas
def sort_entries(cart):
"""Sort a users shopping cart in alphabetically order.
:param cart: dict - a users shopping cart dictionary.
:return: dict - users shopping cart sorted in alphabetical order.
"""
sorted_cart: dict = dict(sorted(cart.items()))
return sorted_cart
def send_to_store(cart, aisle_mapping):
"""Combine users order to aisle and refrigeration information.
:param cart: dict - users shopping cart dictionary.
:param aisle_mapping: dict - aisle and refrigeration information dictionary.
:return: dict - fulfillment dictionary ready to send to store.
"""
fulfillment: dict[str, list] = {}
for item in cart:
fulfillment[item] = [cart[item],
aisle_mapping[item][0], aisle_mapping[item][1]]
fulfillment = dict(sorted(fulfillment.items(), reverse=True))
return fulfillment
def update_store_inventory(fulfillment_cart, store_inventory):
"""Update store inventory levels with user order.
:param fulfillment cart: dict - fulfillment cart to send to store.
:param store_inventory: dict - store available inventory
:return: dict - store_inventory updated.
"""
for item in fulfillment_cart:
new_stock = store_inventory[item][0] - fulfillment_cart[item][0]
store_inventory[item] = [
"Out of Stock" if new_stock <= 0 else new_stock,
store_inventory[item][1],
store_inventory[item][2],
]
return store_inventory