wiki:python/sum

Python Doc


Warum nimmt sum() keine strings?
Re: "count" in verschachtelten Listen?

Examples

Sum positiv and negativ numbers separately

Positive und negative Zahlen aus Liste separat addieren

import random
import sys
import time
import timeit

if sys.version.startswith('3'):
    from functools import reduce
    lambda_ = () 
else:
    range = xrange

numbers = list(range(100000)) + list(range(-100000, 0))
random.shuffle(numbers)

def with_filter():
    sum(filter(lambda e: e > 0, numbers))
    sum(filter(lambda e: e < 0, numbers))

def with_map():
    map(sum, zip(*((0, item) if item < 0 else (item, 0) for 
                   item in numbers)))

def with_lc():
    sum(i for i in numbers if i<0)
    sum(i for i in numbers if i>0)

def with_reduce():
    reduce(lambda pos_neg, next: (pos_neg[0] + next, pos_neg[1]) if
           next >= 0 else (pos_neg[0], pos_neg[1] + next), numbers, (0, 0))

def with_sub():
    p = sum(i for i in numbers if i > 0)
    sum(numbers) - p

def with_for():
    result = [0, 0]
    for n in numbers:
        result[n<0] += n

def with_ifelse():
    n, p = 0, 0
    for number in numbers:
        if number < 0:
            n += number
        else:
            p += number

def start_test(count=5, repeat=3):
    functions = [func for name, func in globals().items() if 
                 name.startswith('with_')]
    result = {}
    timer = time.time
    for func in functions:
        import_ = 'from __main__ import {0}'.format(func.__name__)
        func_ = '{0}()'.format(func.__name__)
        results = timeit.repeat(stmt=func_, setup=import_, timer=timer, 
                                repeat=repeat, number=count)
        result[func.__name__] = min(results), max(results)
    result = sorted(result.items(), key=lambda e: e[0])
    print('{0} repetitions of {1} runs:'.format(repeat, count))
    print('\t\tmin\t\tmax')
    for func, times in result:
        print('{func}:\t{times[0]:f}\t{times[1]:f}'.format(times=times, 
                                                           func=func))

if __name__ == '__main__':
    args = map(int, sys.argv[1:3])
    start_test(*args)

Python 2.6.6

$ python ./measure_sum.py 10 5
5 repetitions of 10 runs:
		min		max
with_filter:	0.856682	0.864453
with_for:	0.387800	0.404242
with_ifelse:	0.282156	0.295538
with_lc:	0.529992	0.540703
with_map:	1.683503	1.728494
with_reduce:	0.761827	0.793188
with_sub:	0.369928	0.388947

Python 3.3.0

$ python3 ./measure_sum.py 10 5
5 repetitions of 10 runs:
		min		max
with_filter:	1.111608	1.166339
with_for:	0.493963	0.498310
with_ifelse:	0.407400	0.417205
with_lc:	0.630200	0.632272
with_map:	1.335373	1.345122
with_reduce:	0.807354	0.809970
with_sub:	0.453200	0.454332
Last modified 6 years ago Last modified on Oct 15, 2013, 4:04:48 PM