fork download
  1. # option 1: string slices
  2. def get_slices_str(n, sizes, n_digits=11):
  3. s = f'{n:0{n_digits}}'
  4. prev = 0
  5. for size in sizes:
  6. yield s[prev : prev + size]
  7. prev += size
  8.  
  9. # option 2: math
  10. def get_slices_int(n, sizes, n_digits=11):
  11. for size in sizes:
  12. n_digits -= size
  13. val, n = divmod(n, 10 ** n_digits)
  14. yield f'{val:0{size}}'
  15.  
  16. from timeit import timeit
  17. from random import sample
  18.  
  19. # generate a sample with 1000 random numbers between 0 and 999999
  20. numbers = sample(range(1000000), 1000)
  21. # execute each test 300 times
  22. params = { 'number' : 300, 'globals': globals() }
  23. sizes = [2, 2, 1, 3, 3]
  24. # execution times are in seconds
  25. print(timeit('for n in numbers:\n " ".join(get_slices_str(n, sizes))', **params))
  26. print(timeit('for n in numbers:\n " ".join(get_slices_int(n, sizes))', **params))
  27.  
Success #stdin #stdout 3.65s 12112KB
stdin
Standard input is empty
stdout
1.0333789922297
2.5941397324204445