fork download
  1. import timeit
  2. import __main__
  3. from itertools import izip, count
  4. from operator import itemgetter
  5. import random
  6.  
  7. N = 100000
  8. L = [1,2,3,4,1,2]
  9.  
  10.  
  11. def test_f_FJ_1():
  12. -min((x, -i) for i, x in enumerate(L))[1]
  13.  
  14. def test_f_FJ_2():
  15. min(range(len(L)), key=lambda i: (L[i], -i))
  16.  
  17. def test_f_FJ_2_modified():
  18. min(range(len(L)), key=lambda i: L[i]-i)
  19.  
  20. def test_f_Michel_Keijzers():
  21. L.reverse()
  22. len(L) - L.index(min(L)) - 1
  23.  
  24. def test_f_user2387370():
  25. len(L) - L[::-1].index(min(L)) - 1
  26.  
  27. def test_f_akson128():
  28. min_val = min(L)
  29. for i in range(len(L)):
  30. if L[i] == min_val:
  31. idx = i
  32.  
  33. def test_f_Stephan():
  34. len(L)-1 - L[::-1].index(min(L))
  35.  
  36. def test_f_iCodez():
  37. max(x for x,y in enumerate(L) if y == min(L))
  38.  
  39. def test_f_ovgolovin():
  40. min(izip(count(len(L)-1,-1), reversed(L)), key=itemgetter(1))[0]
  41.  
  42.  
  43. def main():
  44. names = dir(__main__)
  45. for name in names:
  46. attr = getattr(__main__, name)
  47. if hasattr(attr,'__call__'):
  48. if name.startswith('test_f_'):
  49. init_name = name + '_init'
  50. if hasattr(__main__, init_name):
  51. init = getattr(__main__, init_name)
  52. else:
  53. init = 'from __main__ import {name}'.format(name=name)
  54. t = timeit.Timer(stmt='{name}()'.format(name=name),
  55. setup=init)
  56.  
  57. time = t.timeit(N)
  58. print('{name}: {time}'.format(name=name,time=time))
  59.  
  60.  
  61. print("Small list")
  62. print("=========================")
  63. main()
  64.  
  65.  
  66. L = range(10000)
  67. #random.shuffle(L)
  68. N = 100
  69. print
  70. print("Large list")
  71. print("=========================")
  72. del test_f_iCodez # too slow because of quadratic complexity
  73. main()
Success #stdin #stdout 3.42s 11168KB
stdin
Standard input is empty
stdout
Small list
=========================
test_f_FJ_1: 0.258817911148
test_f_FJ_2: 0.30868601799
test_f_FJ_2_modified: 0.255784034729
test_f_Michel_Keijzers: 0.114651918411
test_f_Stephan: 0.127985954285
test_f_akson128: 0.175076007843
test_f_iCodez: 0.400985956192
test_f_ovgolovin: 0.283308982849
test_f_user2387370: 0.130074977875

Large list
=========================
test_f_FJ_1: 0.254987001419
test_f_FJ_2: 0.330414056778
test_f_FJ_2_modified: 0.24095416069
test_f_Michel_Keijzers: 0.0422029495239
test_f_Stephan: 0.0580480098724
test_f_akson128: 0.129286050797
test_f_ovgolovin: 0.171941041946
test_f_user2387370: 0.0580408573151