sum - :
positive_tally = sum(x for x in seq if x > 0)
negative_tally = sum(x for x in seq if x < 0)
Combining these functions into one function negposwould be simple enough, but probably unnecessary, if you do not do it in several different places.
Out of curiosity, I decided to make an actual time comparison between the generator expression approach and a simple loop for:
code1 = """
data = [-5,5,6,-8,9]
def negpos(seq):
neg, pos = 0, 0
for x in seq:
if x >= 0:
pos += x
else:
neg += x
return neg, pos
"""
code2 = """
data = [-5,5,6,-8,9]
def negpos(seq):
neg = sum(x for x in seq if x < 0)
pos = sum(x for x in seq if x > 0)
return neg, pos
"""
command = "negpos(data)"
timer1 = timeit.Timer(command, code1)
timer2 = timeit.Timer(command, code2)
timer1.repeat()
timer2.repeat()
On my system, a dedicated loop forturns out to be about twice as fast (which is not particularly surprising since the loop runs twice using a generator-based approach, but it’s still interesting to confirm it).
source
share