fork download
  1. import random, string
  2. from collections import Counter, defaultdict
  3. import operator
  4. from itertools import groupby, chain
  5. from timeit import timeit
  6.  
  7.  
  8. def rndstr(len):
  9. return ''.join(random.choice(string.letters) for i in xrange(len))
  10.  
  11. def rnditem():
  12. return (rndstr(20), random.randint(1, 1000))
  13.  
  14. a=[("13.5",100)]
  15. b=[("14.5",100), ("15.5", 100)]
  16. c=[("15.5",100), ("16.5", 100)]
  17. input=[a,b,c]
  18.  
  19.  
  20. def kos(input):
  21. return reduce(operator.add, (Counter(dict(x)) for x in input))
  22.  
  23. def kos2(input):
  24. def u(a,b):
  25. a.update(b)
  26. return a
  27. return reduce(u, (Counter(dict(x)) for x in input))
  28.  
  29. def initial(input):
  30. output=defaultdict(int)
  31. for d in input:
  32. for item in d:
  33. output[item[0]]+=item[1]
  34. return dict(output)
  35.  
  36. def BigYellowCactus(input):
  37. input = sorted(chain(*input), key=lambda x: x[0])
  38. output = {}
  39. for k, g in groupby(input, key=lambda x: x[0]):
  40. output[k] = sum(x[1] for x in g)
  41. return output
  42.  
  43. def merge_with(d1, d2, fn=lambda x, y: x + y):
  44. res = d1.copy()
  45. for key, val in d2.iteritems():
  46. try:
  47. res[key] = fn(res[key], val)
  48. except KeyError:
  49. res[key] = val
  50. return res
  51.  
  52. def astynax(input):
  53. return reduce(merge_with, map(dict,input))
  54.  
  55. dim = 80
  56. input = [[rnditem() for i in xrange(dim)] for j in xrange(dim)]
  57.  
  58. results = [(k.func_name, timeit(lambda: k(input), number=3)) for k in (kos, kos2, initial, BigYellowCactus, astynax)]
  59. results.sort(key=operator.itemgetter(1))
  60. print '\n'.join(str.format('{:20}{}', *x) for x in results)
  61.  
Success #stdin #stdout 1.33s 11312KB
stdin
Standard input is empty
stdout
initial             0.0145859718323
kos2                0.0170421600342
BigYellowCactus     0.0496580600739
astynax             0.0914399623871
kos                 0.857069969177