n00bprogrammer22 - 1 year ago 65
Python Question

# Product dictionary addition and subtraction

I need to write a function that accepts a dictionary as the inventory and also a product_list of (name, number) pairs which indicate when we should update the inventory of that product by adding a certain number to it which could be a negative number.

Once a product is mentioned for the first time it is added to the dictionary and when its count reaches zero it shold remain in the dictionary. If the count ever becomes negative I need to raise a value error.

Example:

``````d = {"apple":50, "pear":30, "orange":25}

ps = [("apple",20),("pear",-10),("grape",18)]

shelve(d,ps)
d
{'pear': 20, 'grape': 18, 'orange': 25, 'apple': 70}

shelve(d,[("apple",-1000)])
Traceback (most recent call last):

ValueError: negative amount for apple
``````

My code is giving either an unexpected EOF error or invalid syntax depending on if I include the last print line. It is definitely not currently accomplishing the goal but I believe this is the format and somewhat the logic I'll need to solve this. I need the function to print 'negative amount for x' where x is the fruit that is negative. Any help on this is appreciated

Code:

``````def shelve(inventory,product_list):
count = 0

try:

for x in product_list:
if x == True:
product_list.append(x)
count += key
else:
return product_list

except ValueError:
print ('negative amount for (product)')

print "hello program starts here"
d = {"apple":50, "pear":30, "orange":25}

ps = [("apple",20),("pear",-10),("grape",18)]

shelve(d,ps)
``````

the important part of your task is to split your problem in sub problems. Using the dict and list data structure is mainly based on iterating over those data structures. Start simple and do one step at a time.So one way to solve the problem could be:

1.) Iterate over the product list (you can print the items to see what is happening). This will be the product loop.

``````for x in ps:
print x
``````

Check how you can access the lists elements with e.g. changing print x to print x[0] or x[1]

2.) Now for every product in the product loop, you need to iterate the inventory and set the inventory to the corresponding values. Start by just iterating the inventory and print its contents. Check out how it works before doing more complicated stuff, play around with it. ^^-d (I just noticed there is a simpler solution than iterating, since its a dict, you will know what to do)

3.) Now add the Value error and Exception stuff

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download