I have to calculate the total value f my stock based on the price per unit and number of units. I have the following code in Python:
prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3, } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, } for key in prices: print key print "price: %s" % prices[key] print "stock: %s" % stock[key] total = 0 for key in prices: total = total + prices[key]*stock[key] print total And I've tried to convert it to a more functional program by replacing the last block with this:
def total(x): if len(x) == 1: return prices[prices.keys()[0]]*stock[prices.keys()[0]] else: return prices[prices.keys()[0]]*stock[prices.keys()[0]] + total(x[1:]) print total(prices) The above code gets this error:
Traceback (most recent call last): File "python", line 30, in <module> File "python", line 28, in total TypeError: unhashable type Can someone please correct my code to a more functional programming version?