我必须根据单位价格和单位数来计算我股票的总价值。我有下面的代码在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
而且我试过用这种替代的最后一个块将其转换为一个功能更强大的程序:
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)
上面的代码得到这个错误:
Traceback (most recent call last):
File "python", line 30, in <module>
File "python", line 28, in total
TypeError: unhashable type
有人可以请更正我的代码更多的功能编程版本?
在Python中通常要避免递归。功能!=递归。 –
哦,对,'StackOverflowError'很糟糕。 – LexieHankins
??停止如此戏剧化。我只是简单地指出,如果您要就如何使用特定语言编写代码提供建议,则不应鼓励使用通常会导致性能较差的构造。 Python不是为递归而构建的,分配一个新的栈帧有很多开销,并且没有tail-call优化。还有一个递归限制。有些情况下,比如走在一棵树上,你知道它并不是很深,在这种情况下,递归实现的简单性可能会超过非递归实现。 –