Another version of this algorithm, which may be more efficient if the list is mostly co-prime, you can simply use range(i, X, i)to generate only multiples i, and then use heapq.mergeto combine iterators so that the returned iterator is sorted.
The last step is to remove duplicates during the game:
import heapq
def all_multiples(multi_list, max_N):
gens = []
for fac in sorted(set(multi_list)):
gens.append(range(fac, max_N, fac))
o = heapq.merge(*gens)
last = None
for val in o:
if val != last:
yield val
last = val
if __name__ == "__main__":
multi_list = [2, 4, 7]
print(list(all_multiples(multi_list, 12)))
source
share