名单技术,我有一个功能,它的名字是positive_negative递归技术,而不是蟒蛇
def positive_negative(list_changes):
""" (list of number) -> (number, number) tuple
list_changes contains a list of float numbers. Return a 2-item
tuple where the first item is the sum of the positive numbers in list_changes and
the second is the sum of the negative numbers in list_changes.
>>> positive_negative([0.01, 0.03, -0.02, -0.14, 0, 0, 0.10, -0.01])
(0.14, -0.17)
"""
我可以用列表技术如下写这个函数:
def positive_negative(list_changes):
pos = sum([item for item in list_changes if item > 0.0])
neg = sum ([item for item in list_changes if item < 0.0])
return pos, neg
,这是一个很好的解决方案。 现在我的问题是如何使用递归技术来解决相同的功能,我已经尝试了下面的代码,但不幸的是有一些错误。
def positive_negative(list_changes):
pos = 0.0
neg = 0.0
if len(list_changes)== 0:
pos =+ 0.0
neg =+ 0.0
return pos,neg
else:
if list_changes[0] > 0.0 :
pos =+ list_changes[0]
else:
neg =+ list_changes[0]
positive_negative(list_changes[1:])
return pos,neg
你能帮我找出我的错误是什么,以及如何得到正确的递归函数。
谢谢
作为一个侧面说明,解决问题的更好方法是使用生成器表达式而不是列表理解 - 只是删除方括号,而列表版本的工作原理完全相同,除了不必为了传递而构建整个列表它总结,它建立它懒惰。 – abarnert 2013-04-03 23:54:36
谢谢你,宝贵的意见。 – mazlor 2013-04-03 23:59:20