Reputation: 3087
Consider the iterators count(3,3)
and count(5,5)
. How can I create a iterator that outputs only the numbers that occur in either count(3,3)
and count(5,5)
?
Upvotes: 1
Views: 2508
Reputation: 71044
For the sake of having an answer to this question, OP accepted (x for x in count(3) if not x%3 or not x%5)
as a solution in the comments. What follows below should work for the general case so long as duplicates are acceptable. If duplicates aren't acceptable, it could be wrapped in a function that stored its output in a set for further reference but now we're making assumptions on the total size that it will end up being.
one way would just be to interleave the two. This assumes that they both have the same cardnality. This will also create duplicates as pointed out in the comments.
import itertools
def union(it1, it2):
return (item for pair in itertools.izip(it1, it2) for item in pair)
If they have different cardnalities, then you'll end up truncating one of the two. Here's a more general solution
import itertools
def union(it1, it2):
it1, it2 = iter(it1), iter(it2)
for item in (item for pair in itertools.izip(it1, it2) for item in pair):
yield item
for it in (it1, it2):
for item in it:
yield item
Upvotes: 1