Created
July 27, 2017 20:07
-
-
Save toonarmycaptain/22d6f14681c4cf11dea2044df54a0861 to your computer and use it in GitHub Desktop.
Automate the Boring Stuff Chpt 5 - Fantasy Game Inventory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} | |
#def displayInventory(inventory): | |
# total_items = 0 | |
# for item in inventory: | |
# print(str(inventory[item])+' '+item) | |
# total_items += inventory[item] | |
# print("Total number of items: "+str(total_items)) | |
# This worked but I like the following better: | |
def displayInventory(inventory): | |
total_items = 0 | |
for item, quantity in inventory.items(): | |
print(str(quantity)+' '+item) | |
total_items += quantity | |
print("Total number of items: "+str(total_items)) | |
displayInventory(stuff) | |
def addToInventory(inventory, addedItems): | |
for item in addedItems: | |
inventory.setdefault(item, 0) #this adds a (defaulted to zero value) key to the inventory dict if it's not already there | |
inventory[item] += 1 #and this increases that value by one, each time that item appears in the loot list | |
return inventory | |
inv = {'gold coin': 42, 'rope': 1} | |
displayInventory(inv) | |
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] | |
inv = addToInventory(inv, dragonLoot) | |
displayInventory(inv) |
Author
toonarmycaptain
commented
Jun 28, 2021
Thanks man, you are clever!
I just want to share my code on how I solve this exercise :)
`inventory = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addInventory(inventory, loots):
for loot in loots:
addedQty = 0
if loot in inventory.keys():
addedQty += 1
inventory[loot] += addedQty
else:
inventory.setdefault(loot, 1)
return inventory
def displayInventory(inventory):
total = 0
for key, value in inventory.items():
print(str(value) + ' ' + key)
total += value
print('Total number of items: ' + str(total))
displayInventory(addInventory(inventory, dragonLoot))`
thank you <3
thank you!
I was having a hard time with the second part of the code.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment