fork(6) 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(dicts, fn=lambda x, y: x + y):
  44. res = dict(dicts[0])
  45. for dic in dicts[1:]:
  46. for key, val in dic:
  47. try:
  48. res[key] = fn(res[key], val)
  49. except KeyError:
  50. res[key] = val
  51. return res
  52.  
  53. astynax = merge_with
  54.  
  55. def astynax2(input):
  56. res = defaultdict(int)
  57. for k, v in chain(*input):
  58. res[k] += v
  59. return res
  60.  
  61. dim = 80
  62. input = [[rnditem() for i in xrange(dim)] for j in xrange(dim)]
  63.  
  64. results = [(k.func_name, timeit(lambda: k(input), number=3)) for k in (
  65. kos, kos2, initial, BigYellowCactus, astynax, astynax2)]
  66. results.sort(key=operator.itemgetter(1))
  67. print '\n'.join(str.format('{:20}{}', *x) for x in results)
  68.  
Success #stdin #stdout 1.31s 11296KB
stdin
Standard input is empty
stdout
astynax2            0.0104920864105
initial             0.0144059658051
kos2                0.0176160335541
merge_with          0.0303680896759
BigYellowCactus     0.0476379394531
kos                 0.885484218597