Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have the code below to get an infinite generator of the products of an iterable (e.g. for the iterable "ABC" it should return

A, B, C, AA, AB, AC, BA, BB, BC, CA, CB, CC, AAA, AAB, AAC etc.

for product in (itertools.product("ABC", repeat=i) for i in itertools.count(0)):
    for each_tuple in product:
        print(each_tuple)

How would I remove the nested for loop, or is there a better approach?

share|improve this question
1  
you can write itertools.count() instead of .count(0). :) –  flornquake Sep 15 '13 at 20:05

1 Answer 1

up vote 4 down vote accepted

Well, you effectively have 3 nested loops including the generator comprehension, which you can reduce to two just by simplifying:

def get_products(string):
    for i in itertools.count(0):
        for product in itertools.product(string, repeat=i):
            yield product

Or if you are intent on putting it in a single line, use chain:

products_generator = itertools.chain.from_iterable(itertools.product("ABC", repeat=i)
                                                   for i in itertools.count(0))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.