How to get Cartesian product of two iterables when one of them is infinite

2024/11/16 3:44:29

Let's say I have two iterables, one finite and one infinite:

import itertoolsteams = ['A', 'B', 'C']
steps = itertools.count(0, 100)

I was wondering if I can avoid the nested for loop and use one of the infinite iterators from the itertools module like cycle or repeat to get the Cartesian product of these iterables.

The loop should be infinite because the stop value for steps is unknown upfront.

Expected output:

$ python3 test.py  
A 0
B 0
C 0
A 100
B 100
C 100
A 200
B 200
C 200
etc...

Working code with nested loops:

from itertools import count, cycle, repeatSTEP = 100 
LIMIT = 500
TEAMS = ['A', 'B', 'C']def test01():for step in count(0, STEP):for team in TEAMS:print(team, step)if step >= LIMIT:  # Limit for testingbreaktest01()
Answer

Try itertools.product

from itertools import product
for i, j in product(range(0, 501, 100), 'ABC'):print(j, i)

As the docs say product(A, B) is equivalent to ((x,y) for x in A for y in B). As you can see, product yield a tuple, which mean it's a generator and do not create a list in memory in order to work properly.

This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:

def product(*args, **kwds):# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111pools = map(tuple, args) * kwds.get('repeat', 1)result = [[]]for pool in pools:result = [x+[y] for x in result for y in pool]for prod in result:yield tuple(prod)

But you can't use itertools.product for infinite loop due to a known issue:

According to the documentation, itertools.product is equivalent tonested for-loops in a generator expression. But,itertools.product(itertools.count(2010)) is not.

>>> import itertools
>>> (year for year in itertools.count(2010))
<generator object <genexpr> at 0x026367D8>
>>> itertools.product(itertools.count(2010))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
MemoryError

The input to itertools.product must be a finite sequence of finiteiterables.

For infinite loop, you can use this code.

https://en.xdnf.cn/q/118979.html

Related Q&A

Function to create nested dictionary from lists [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Pygame not using specified font

So I am having a problem in pygame where I specify the font and size to use, but when my program is run, the font and size are the default.Here is where I define the textdef font(self):*****FATAL - THI…

port management in python/flask application

I am writing a REST API using the micro framework Flask with python programming language. In the debug mode the application detect any change in source code and restart itself using the same host and p…

using def with tkinter to make simple wikipedia app in python

I am beginner in python. I am trying to make a python wiki app that gives you a summary of anything that you search for. My code is below:import wikipediaquestion = input("Question: ")wikiped…

Only length-1 arrays can be converted to Python scalars with log

from numpy import * from pylab import * from scipy import * from scipy.signal import * from scipy.stats import * testimg = imread(path) hist = hist(testimg.flatten(), 256, range=[0.0,1.0])[0] hist…

Deploying Django with apache using wsgi.py

Im trying to deploy a Django project on a linode server that has apache, some other django projects and a php project on it. Also my project is in a virualenv and the other django projects arent.My Dja…

Building a decision tree using user inputs for ordering goods

I am trying to program a decision tree to allow customers to order goods based on their input. So far, I have devised a nested if-elif conditional structure to decide if customer want to order what or…

How to de-serialize the spark data frame into another data frame [duplicate]

This question already has answers here:Explode array data into rows in spark [duplicate](3 answers)Closed 4 years ago.I am trying to de-serialize the the spark data frame into another data frame as exp…

How to pull specific key from this nested dictionary?

{"newData": [{"env1": [{"sins": [{"host": "test.com","deployTime": "2015-07-23 11:54 AM",…}],"name": “hello”}, {"…

Dropping cell if it is NaN in a Dataframe in python

I have a dataframe like this.Project 4 Project1 Project2 Project3 0 NaN laptio AB NaN 1 NaN windows ten NaN 0 one NaN NaN 1 …