Skip to content

Instantly share code, notes, and snippets.

@mudspringhiker
Last active July 25, 2017 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mudspringhiker/4e24bc8f4398dfe6535ec2e6baa485d5 to your computer and use it in GitHub Desktop.
Save mudspringhiker/4e24bc8f4398dfe6535ec2e6baa485d5 to your computer and use it in GitHub Desktop.
Grocery List Exercise (PyLadies Austin 07-24-17)
# Write a program that creates a unique grocery list.
# There must be a function to add an item to the list
# There must be a function to get the list.
# This means you can look at the list at anytime
# and add an item at any time.
# If you want to add a challenge, also have the ability to
# specify the amount you need to purchase of each item
from collections import defaultdict
class GroceryList():
def __init__(self):
self.items = defaultdict(int)
# self.items = {} # set grocery list empty
print("Grocery list has been created.")
def add_item(self, item, quantity):
self.items[item] += quantity
# if item not in self.items:
# self.items[item] = quantity
# else:
# self.items[item] += quantity
print("{} {} added to grocery list".format(quantity, item))
return self.items
def get_list(self):
return self.items
def main():
sonachi_grocery = GroceryList() # instantiate a GroceryList object
print("Sonachi's grocery list: {}".format(sonachi_grocery.get_list()))
print()
sonachi_grocery.add_item("Colgate", 2) # add item to the list
print("Sonachi's grocery list: {}".format(sonachi_grocery.get_list()))
print()
# adding a lot of items to the list using a for loop
items = [("shampoo", 1), ("shrimp", 1), ("noodles", 2), ("hand wash", 2)]
for item in items:
sonachi_grocery.add_item(item[0], item[1])
print("Sonachi's grocery list: {}".format(sonachi_grocery.get_list()))
print()
# testing that the object increments items that are already present in the grocery list
sonachi_grocery.add_item("shrimp", 1)
print("Sonachi's grocery list: {}".format(sonachi_grocery.get_list()))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment