List of items for Python fun games

Posted by liljester on Wed, 31 Jul 2019 20:42:45 +0200

Python programming is a quick way to practice project topics. Welcome to identify and optimize!
You're creating a fun video game. The data structure used to model the player's inventory is a word.
Dian. The key is a string describing the item in the list. The value is an integer value indicating how many items the player has.
Product. For example, dictionary values {rope': 1,'torch': 6,'gold coin': 42,'dagger': 1,'arrow': 12} mean play.
There is a rope, six torches, 42 gold coins and so on.
Write a function called displayInventory(), which accepts any list of possible items and displays them as follows:

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))
displayInventory(stuff)

Operation results:

Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62

List-to-dictionary function for list of fun game items
Suppose the booty of conquering a dragon is represented as a list of strings like this:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function called addToInventory(inventory, addedItems), where the inventory parameter
It is a dictionary that represents the player's list of items (like the previous item), and the addedItems parameter is a list.
Like dragon Loot.
The addToInventory() function should return a dictionary representing the updated list of items. Note that column
A table can contain multiple identical items. Your code might look like this:

def addToInventory(inventory, addedItems):
# your code goes here

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

New code:

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))
#displayInventory(stuff)

def addToInventory(inventory, addedItems):
# your code goes here
    for i in addedItems:
        if i in inventory.keys():
            inventory[i] += 1
        else:
            inventory.setdefault(i,1)
    return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

Operation results:

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48

Topics: Python Ruby Programming