#!/usr/bin/env python
# coding: utf-8
# from pprint import pprint as print
# https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array
# https://www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods
from __future__ import print_function
import random
from functools import reduce
import time
N = int(1e6)
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
# print(method.__name__, str(te), str(ts))
print ('%r %5.5f msec' %(method.__name__, 1e3*(te-ts)))
return result
return timed
def data():
return map(lambda x: random.randint(-N, N), range(N))
@timeit
def summarize(_):
pos, neg = 0, 0
pos = sum(map(lambda x: x if x > 0 else 0, _))
neg = sum(map(lambda x: x if x < 0 else 0, _))
return neg, pos
@timeit
def summarize_2(_):
pos, neg = 0, 0
for e in _:
if e < 0:
neg += e
else:
pos += e
return neg, pos
def pos_reducer(x, y):
if (x > 0 and y > 0):
return x + y
if (x > 0 and y <= 0):
return x
if (y > 0 and x <= 0):
return y
return 0
def neg_reducer(x, y):
if (x < 0 and y < 0):
return x + y
if (x < 0 and y >= 0):
return x
if (y < 0 and x >= 0):
return y
return 0
@timeit
def summarize_(_):
pos, neg = 0, 0
pos = reduce(pos_reducer, _)
neg = reduce(neg_reducer, _)
return neg, pos
def main():
arr = list(data())
print(summarize(arr))
print(summarize_(arr))
print(summarize_2(arr))
# arr.sort()
print(summarize(arr))
print(summarize_(arr))
print(summarize_2(list(sorted(arr))))
# print(summarize_(arr[:]))
if __name__ == '__main__':
main()