Advertisement
Guest User

Untitled

a guest
Sep 30th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import itertools
  2.  
  3. def miyagi_product(somelists, first, last):
  4. first_index, radix = 0, 1
  5. for sub_list, sub_first in zip(reversed(somelists), reversed(first)):
  6. first_index += sub_list.index(sub_first) * radix
  7. radix *= len(sub_list)
  8.  
  9. for element in itertools.islice(itertools.product(*somelists), first_index, None):
  10. yield element
  11. if x == last:
  12. break
  13.  
  14. #get the nth product of `lists`
  15. def product_by_idx(lists, n):
  16. result = []
  17. for seq in reversed(lists):
  18. n, x = divmod(n, len(seq))
  19. result.append(seq[x])
  20. return result[::-1]
  21.  
  22. #find n such that product(lists, n) == target
  23. def idx_from_product(lists, target):
  24. n = 0
  25. for x, seq in zip(target, lists):
  26. n *= len(seq)
  27. n += seq.index(x)
  28. return n
  29.  
  30. def kevin_product(lists, from_, to_):
  31. start = idx_from_product(lists, from_)
  32. end = idx_from_product(lists, to_)
  33. for n in range(start, 1+end):
  34. yield product_by_idx(lists, n)
  35.  
  36. somelists = [
  37. [0,1,2,3,4,5,6,7,8,9],
  38. [0,1,2,3,4,5,6,7,8,9],
  39. [0,1,2,3,4,5,6,7,8,9],
  40. [0,1,2,3,4,5,6,7,8,9],
  41. [0,1,2,3,4,5,6,7,8,9],
  42. [0,1,2,3,4,5,6,7,8,9],
  43. [0,1,2,3,4,5,6,7,8,9],
  44. ]
  45.  
  46. import time
  47. args = (somelists, (9,9,9,9,9,9,0), (9,9,9,9,9,9,9))
  48.  
  49. start = time.time()
  50. for x in miyagi_product(*args):
  51. pass
  52. print(f"Completed in {time.time() - start} seconds")
  53.  
  54. start = time.time()
  55. for x in kevin_product(*args):
  56. pass
  57. print(f"Completed in {time.time() - start} seconds")
  58.  
  59. #results on my machine:
  60. #Completed in 0.348247766494751 seconds
  61. #Completed in 0.0009999275207519531 seconds
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement