fork download
  1. import timeit
  2.  
  3.  
  4. def div11(n):
  5. acc, sign = 0, 1
  6.  
  7. while n:
  8. n, r, sign = n // 10, n % 10, -sign
  9. acc += r * sign
  10.  
  11. acc = abs(acc)
  12. return div11(acc) if acc >= 11 else acc == 0
  13.  
  14.  
  15. def is_divisible_by_11(num):
  16. digits = list(str(num))
  17. odd = sum(map(int, digits[0::2]))
  18. even = sum(map(int, digits[1::2]))
  19. diff = abs(odd - even)
  20. if diff < 11:
  21. return diff == 0
  22. else:
  23. return is_divisible_by_11(diff)
  24.  
  25. def test1():
  26. for n in range(1234):
  27. res = div11(n)
  28.  
  29. def test2():
  30. for n in range(1234):
  31. res = is_divisible_by_11(n)
  32.  
  33. def is_divisible_by_11_human_version(x):
  34. return x % 11 == 0
  35.  
  36. def test3():
  37. for n in range(1234):
  38. res = is_divisible_by_11_human_version(n)
  39.  
  40. print(timeit.timeit(test1, number=1000))
  41. print(timeit.timeit(test2, number=1000))
  42. print(timeit.timeit(test3, number=1000))
Success #stdin #stdout 3.23s 9632KB
stdin
Standard input is empty
stdout
0.7617890387773514
2.3372320979833603
0.11346355080604553