Created
January 28, 2019 15:25
-
-
Save santosh/158377151fee68faaa6380b93436af2b to your computer and use it in GitHub Desktop.
Inventory game. Exercise to https://automatetheboringstuff.com/chapter5/
This file contains hidden or 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
# You are creating a fantasy video game. The data structure to model the player's inventory will be a dictionary where the keys are string values describing the item in the inventory and the value is an integer values defailing how many of that item the player has. For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, and so on. | |
# Write a function named displayInventory() that would take any possible "inventory" and display it like the following: | |
# Inventory: | |
# 12 arrow | |
# 42 gold coin | |
# 1 rope | |
# 6 torch | |
# 1 dagger | |
# Total number of items: 62 | |
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} | |
addedItems = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] | |
def displayInventory(inventory): | |
"""Display a passed dictionary in human readable manner. | |
Args: | |
dict data: dictionary of items and amounts | |
""" | |
for item, amount in inventory.items(): | |
print(amount, item) | |
print("Total number of items:", sum(inventory.values())) | |
# displayInventory(inventory) | |
# Imagine that a vanquished dragon’s loot is represented as a list of strings like this: | |
# dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] | |
# Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item | |
def addToInventory(inventory, addedItems): | |
"""Adds item to the inventory | |
Args: | |
dict inventory: base inventory | |
list addedItems: item to add | |
Returns: | |
dict inventory: new inventory after adding items | |
""" | |
new_dict = {} | |
for item in addedItems: | |
new_dict.setdefault(item, 0) | |
new_dict[item] += 1 | |
for item, amount in new_dict.items(): | |
if item in inventory: | |
inventory[item] += amount | |
return inventory | |
print(addToInventory(inventory, addedItems)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment