2

Is there a way to find common items in two Python generators, besides reading one into a list? You can't assume anything about the ordering of the items.

As a bad example:

import random
a = (random.randint(1, 50000) for _ in xrange(300))
b = (random.randint(3500, 3700) for _ in xrange(50))      

# do A and B have any elements in common?
3
  • Perhaps you would edit this and post a little more information and some code? Commented Jan 26, 2012 at 21:14
  • Define "common". Are you asking how to find the union between the two generators? Commented Jan 26, 2012 at 21:18
  • I updated the question to make it more clear. Commented Jan 26, 2012 at 21:26

1 Answer 1

5

If you can't assume anything about the order of the items, then you can't logically do this without reading one of the generators entirely into a list (or a set which might make more sense if you don't care about duplicates within one generator).

To illustrate this, let's assume that the only two identical elements were the first item of the one generator and the last item of the other generator (but you don't know which is which). You need to have exhausted one of the generators entirely to make sure you know which common elements there are.

How to do it with sets:

>>> import random
>>> a = (random.randint(1, 50000) for _ in xrange(300))
>>> b = (random.randint(3500, 3700) for _ in xrange(50))
>>> set(a).intersection(set(b))
set([])
>>> a = (random.randint(1, 50000) for _ in xrange(300))
>>> b = (random.randint(3500, 3700) for _ in xrange(50))
>>> set(a).intersection(set(b))
set([3634])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.