Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools
- def mixedBaseCounter(radixes, state=None):
- if state is None:
- state = [0] * len(radixes)
- while True:
- yield state
- state[-1] += 1
- for idx in range(len(radixes)-1, 0, -1):
- if state[idx] == radixes[idx]:
- state[idx] = 0
- state[idx-1] += 1
- else:
- break
- if state[0] == radixes[0]:
- return
- def pm_product(lists, from_, to_):
- starting_indices = [lists[i].index(x) for i,x in enumerate(from_)]
- ending_indices = [lists[i].index(x) for i,x in enumerate(to_)]
- radixes = [len(seq) for seq in lists]
- for indices in mixedBaseCounter(radixes, starting_indices):
- result = [lists[i][idx] for i, idx in enumerate(indices)]
- yield result
- if indices == ending_indices:
- break
- def miyagi_product(somelists, first, last):
- first_index, radix = 0, 1
- for sub_list, sub_first in zip(reversed(somelists), reversed(first)):
- first_index += sub_list.index(sub_first) * radix
- radix *= len(sub_list)
- for element in itertools.islice(itertools.product(*somelists), first_index, None):
- yield element
- if x == last:
- break
- #get the nth product of `lists`
- def product_by_idx(lists, n):
- result = []
- for seq in reversed(lists):
- n, x = divmod(n, len(seq))
- result.append(seq[x])
- return result[::-1]
- #find n such that product(lists, n) == target
- def idx_from_product(lists, target):
- n = 0
- for x, seq in zip(target, lists):
- n *= len(seq)
- n += seq.index(x)
- return n
- def kevin_product(lists, from_, to_):
- start = idx_from_product(lists, from_)
- end = idx_from_product(lists, to_)
- for n in range(start, 1+end):
- yield product_by_idx(lists, n)
- somelists = [
- [0,1,2,3,4,5,6,7,8,9],
- [0,1,2,3,4,5,6,7,8,9],
- [0,1,2,3,4,5,6,7,8,9],
- [0,1,2,3,4,5,6,7,8,9],
- [0,1,2,3,4,5,6,7,8,9],
- [0,1,2,3,4,5,6,7,8,9],
- [0,1,2,3,4,5,6,7,8,9],
- ]
- import time
- args = (somelists, (9,9,9,0,0,0,0), (9,9,9,9,9,9,9))
- start = time.time()
- for x in miyagi_product(*args):
- pass
- print(f"Completed in {time.time() - start} seconds")
- start = time.time()
- for x in kevin_product(*args):
- pass
- print(f"Completed in {time.time() - start} seconds")
- start = time.time()
- for x in pm_product(*args):
- pass
- print(f"Completed in {time.time() - start} seconds")
- #results on my machine:
- #Completed in 0.38527798652648926 seconds
- #Completed in 0.1340954303741455 seconds
- #Completed in 0.13209939002990723 seconds
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement