0
\$\begingroup\$

This is based upon an exercise in chapter 5 of Automate the Boring Stuff with Python.

This code contains functions addToInventory which modifies a given inventory of items to add new items as well as update existing items and displayInventory which displays the items and their values. The main operation is adding the contents of a list dragonloot to inventory inv.

I have tried to do this in two ways, one by calling addToInventory and after that calling displayInventory. This method leads to errors. Another way I tried was by printing the new inventory values within addtoInventory. This works fine. Why doesn't the first method work? I have put both the methods as comments within my code, indicated by """ """.

I know C++ pretty well, but I'm new to Python. Expected result: Inventory: gold coin: 45 rope:1 dagger:1 ruby:1 Total number of items is 48

def addToInventory(inventory, addedItems):
    draft = {}
    for i in addedItems:
        if (i not in draft):
            draft[i]=1
        else:
            draft [i]= draft [i] + 1
    for i in draft:
        if i not in inventory:
            inventory[i]=draft[i]
        else:
            inventory[i] = inventory[i]+draft[i]
    """for i in inventory:
        print(str(inventory[i]) + " " + str(i))"""


def displayInventory(inventory):
    print ("Inventory: ")
    total=0
    for i in inventory.items():
        total+=1
        print (str(inventory[i])+" "+str(i))
    print("Total number of items is"+str(total))


    inv = {'gold coin': 42, 'rope': 1}
    dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
    inv = addToInventory(inv, dragonLoot)
    """displayInventory(inv) when I use this line in place of above comment I get errors"""
\$\endgroup\$
3
  • 1
    \$\begingroup\$ please add the expected result to your code. What will inventory be after you performed your function? \$\endgroup\$ Jul 4, 2019 at 5:18
  • 2
    \$\begingroup\$ Please note that explaining your own code to you is usually considered off-topic here on Code Review. \$\endgroup\$
    – AlexV
    Jul 4, 2019 at 8:25
  • \$\begingroup\$ Thanks for letting me know, in case I have doubts in my code is there any chat or somewhere where I could ask? \$\endgroup\$
    – Hema
    Jul 5, 2019 at 8:11

1 Answer 1

1
\$\begingroup\$

You overwrite inv with the return value of addToInventory

inv = addToInventory(inv, dragonLoot)

Yet add to inventory does not return anything. In order to first get your code to work, just return the inventory:

def addToInventory(inventory, addedItems):
    draft = {}
    for i in addedItems:
        if (i not in draft):
            draft[i]=1
        else:
            draft [i]= draft [i] + 1
    for i in draft:
        if i not in inventory:
            inventory[i]=draft[i]
        else:
            inventory[i] = inventory[i]+draft[i]
    return inventory

And then lets improve that function using the collections library such as:

from collections import Counter

def addToInventory(inv, loot):
    loot_counter = Counter(loot)
    return dict(loot_counter + Counter(inv))

Further, for the second displayInventory function, you iterate over dict.items(), yet you then try to use the item itself as an index. Instead iterate over dict.keys() and you will be fine:

def displayInventory(inventory):
    print ("Inventory: ")
    total=0
    for i in inventory.keys():
        total+=1
        print (str(inventory[i])+" "+str(i))
    print("Total number of items is"+str(total))
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.