patternpythonMinor
Python infinite product generator
Viewed 0 times
infinitepythonproductgenerator
Problem
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.
How would I remove the nested for loop, or is there a better approach?
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?
Solution
Well, you effectively have 3 nested loops including the generator comprehension, which you can reduce to two just by simplifying:
Or if you are intent on putting it in a single line, use
def get_products(string):
for i in itertools.count(0):
for product in itertools.product(string, repeat=i):
yield productOr 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))Code Snippets
def get_products(string):
for i in itertools.count(0):
for product in itertools.product(string, repeat=i):
yield productproducts_generator = itertools.chain.from_iterable(itertools.product("ABC", repeat=i)
for i in itertools.count(0))Context
StackExchange Code Review Q#31313, answer score: 4
Revisions (0)
No revisions yet.