473,769 Members | 1,959 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

nested for loop

Hi,

I want to iterate over all 2x2 matrices with elements in range 0..25
(crypto-stuff).

To produce them, first I wrote a fourfold nested for loop:

M=26
for a in range(M):
for b in range (M):
for c in range (M):
for d in range (M):
matr = [[a,b],[c,d]]
(dosomething)

Then I had a look in comp.lang.pytho n and found:
for (a,b,c,d) in [(x,y,z,t) for x in range(M)
for y in range(M)
for z in range(M)
for t in range(M)] :
matr = [[a,b],[c,d]]

Is there a shorter (and probably, with respect to exec time, faster)
way to write such a 4for loop?
(I want to scan 3x3, 4x4 matrices too (;-)

-- Wolfgang
Jul 18 '05 #1
8 1941
wj****@web.de (Wolfgang Buechel) writes:
for (a,b,c,d) in [(x,y,z,t) for x in range(M)
for y in range(M)
for z in range(M)
for t in range(M)] :
matr = [[a,b],[c,d]]


Try assigning range(M) to a variable instead of creating four copies
of it. For larger ranges, experiment using xrange instead.
Jul 18 '05 #2
Wolfgang Buechel wrote:
I want to iterate over all 2x2 matrices with elements in range 0..25
(crypto-stuff).

To produce them, first I wrote a fourfold nested for loop:

M=26
for a in range(M):
for b in range (M):
for c in range (M):
for d in range (M):
matr = [[a,b],[c,d]]
(dosomething)

Then I had a look in comp.lang.pytho n and found:
for (a,b,c,d) in [(x,y,z,t) for x in range(M)
for y in range(M)
for z in range(M)
for t in range(M)] :
matr = [[a,b],[c,d]]

Is there a shorter (and probably, with respect to exec time, faster)
way to write such a 4for loop?


Hmm... why would you want something shorter, as it would
probably be less readable? Also, how fast do you need it
to run, or how many times faster than the above would you
like it to run?

(The second one is a facetious question... the first is
more serious. In effect: what's wrong with what you have?)

-Peter
Jul 18 '05 #3

"Wolfgang Buechel" <wj****@web.d e> wrote in message
news:46******** *************** ***@posting.goo gle.com...
Hi,

I want to iterate over all 2x2 matrices with elements in range 0..25
(crypto-stuff).

To produce them, first I wrote a fourfold nested for loop:

M=26
for a in range(M):
for b in range (M):
for c in range (M):
for d in range (M):
matr = [[a,b],[c,d]]
(dosomething)
This is completely clear and space efficient.
Then I had a look in comp.lang.pytho n and found:
Oh dear...
for (a,b,c,d) in [(x,y,z,t) for x in range(M)
for y in range(M)
for z in range(M)
for t in range(M)] :
matr = [[a,b],[c,d]]
This is less clear. It took me about 10 seconds (versus 1) to see as
equivalent. It produces a list with M**4 elements that you don't actually
need and soon throw away.
Is there a shorter (and probably, with respect to exec time, faster)
way to write such a 4for loop?


Write a C extension, maybe with Pyrex. However, an hour of your time is
worth lots of hours of PC time. But for a million runs, it might be worth
it.

Terry J. Reedy


Jul 18 '05 #4
"Wolfgang Buechel" <wj****@web.d e> wrote in message
news:46******** *************** ***@posting.goo gle.com...
Hi,

I want to iterate over all 2x2 matrices with elements in range 0..25
(crypto-stuff). [snip] Is there a shorter (and probably, with respect to exec time, faster)
way to write such a 4for loop?
(I want to scan 3x3, 4x4 matrices too (;-)

-- Wolfgang


Hi.

The following code isn't necessarily shorter or faster (or more readable),
but it's a bit more general:

# slightly modified code from
http://twistedmatrix.com/wiki/python/PostYourCode
def sequences(n, things):
"generates sequences of n items from a set of things"
if n == 0:
yield []
else:
for x in things:
for y in sequences(n-1, things):
yield [x] + y

def nXn_matrices(n, elements):
"generates nXn matrices from elements"
for s in sequences(n*n, elements):
yield [s[i*n:(i+1)*n] for i in xrange(n)]

# we'll try it over a small range ...
M = 3
for m in nXn_matrices(2, range(M)):
print m

Output:
[[0, 0], [0, 0]]
[[0, 0], [0, 1]]
[[0, 0], [0, 2]]
[[0, 0], [1, 0]]
[[0, 0], [1, 1]]
[[0, 0], [1, 2]]
[[0, 0], [2, 0]]
....
....
[[2, 2], [2, 0]]
[[2, 2], [2, 1]]
[[2, 2], [2, 2]]

# now 3X3 ... this takes a _l_o_n_g_ time ...
M = 3
for m in nXn_matrices(3, range(M)):
print m

Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 1]]
[[0, 0, 0], [0, 0, 0], [0, 0, 2]]
[[0, 0, 0], [0, 0, 0], [0, 1, 0]]
[[0, 0, 0], [0, 0, 0], [0, 1, 1]]
[[0, 0, 0], [0, 0, 0], [0, 1, 2]]
....
....
[[2, 2, 2], [2, 2, 2], [2, 1, 0]]
[[2, 2, 2], [2, 2, 2], [2, 1, 1]]
[[2, 2, 2], [2, 2, 2], [2, 1, 2]]
[[2, 2, 2], [2, 2, 2], [2, 2, 0]]
[[2, 2, 2], [2, 2, 2], [2, 2, 1]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]

I'm believe there are several opportunities for optimization both in the
code and in the algorithm (for instance, it may be possible to take
advantage of repetition in the sub-matrices), but I won't be trying that
now.

Good luck with what you're doing,
Sean
Jul 18 '05 #5

"Sean Ross" <sr***@connectm ail.carleton.ca > wrote in message
news:VD******** ************@ne ws20.bellglobal .com...
[snip]
# slightly modified code from
http://twistedmatrix.com/wiki/python/PostYourCode
def sequences(n, things):
"generates sequences of n items from a set of things"
if n == 0:
yield []
else:
for x in things:
for y in sequences(n-1, things):
yield [x] + y

def nXn_matrices(n, elements):
"generates nXn matrices from elements"
for s in sequences(n*n, elements):
yield [s[i*n:(i+1)*n] for i in xrange(n)] [snip] [i] believe there are several opportunities for optimization both in the
code and in the algorithm (for instance, it may be possible to take
advantage of repetition in the sub-matrices), but I won't be trying that
now.


Looks like I'll be trying it now after all:

def nXn_matrices2(n , elements):
for m in sequences(n, list(sequences( n, elements))):
yield m

This is slightly faster than the first version, but it has more overhead
since it builds a list of the submatrices. That could be problem. It can
probably be avoided, but I haven't figured out how to do it just yet. We'll
see what happens.

Sean

Jul 18 '05 #6
wj****@web.de (Wolfgang Buechel) wrote:
I want to iterate over all 2x2 matrices with elements in range 0..25
(crypto-stuff).

To produce them, first I wrote a fourfold nested for loop:

M=26
for a in range(M):
for b in range (M):
for c in range (M):
for d in range (M):
matr = [[a,b],[c,d]]
(dosomething)
[snip]
Is there a shorter (and probably, with respect to exec time, faster)
way to write such a 4for loop?
(I want to scan 3x3, 4x4 matrices too (;-)


This question is very much related to the one in a thread below here
(titled "Inverse of int(s, base)?"). In fact with a small adaptation
that code can produce this kind of matrices:

from itertools import islice

def tobase(i,base,d igits):
R = []
for j in xrange(digits):
i,k = divmod(i,base)
R.append(k)
R.reverse()
return R

def as_matrix(R,row s,cols):
it = iter(R)
return[list(islice(it, cols)) for i in xrange(rows)]

def test():
for i in range(10):
R = tobase(i,25,6)
print as_matrix(R,3,2 )

if __name__=='__ma in__':
test()

Anton
Jul 18 '05 #7
wj****@web.de (Wolfgang Buechel) wrote in message news:<46******* *************** ****@posting.go ogle.com>...
Hi,

I want to iterate over all 2x2 matrices with elements in range 0..25
(crypto-stuff).


Try generators (new in Python 2.3.3).
There is an example you can/must adapt:
Look at your Python installation:

(PythonPath)/Lib/test/test_generators .py
def conjoin()

and in the whatsnew-documentation:

http://www.python.org/doc/2.3.3/what...enerators.html

--W.
Jul 18 '05 #8
Dan Bishop wrote:
What you can do to make your code faster (if you don't change matr
once it's created) is to precompute the 676 possible matrix rows.

ELEMENT_RANGE = range(26)
MATRIX_ROWS = [[x, y] for x in ELEMENT_RANGE
for y in ELEMENT_RANGE]
for row1 in MATRIX_ROWS:
for row2 in MATRIX_ROWS:
matr = [row1, row2]

That takes only 532 ms -- almost 3 times faster than the original.


Nice. Another speed gain (from 435 to 246ms on my machine) is in for you if
you use tuples instead of lists. And if you allow for somewhat less elegant
code that builds on your recipe,

from itertools import izip, repeat
ELEMENT_RANGE = range(26)
MATRIX_ROWS = [(x, y) for x in ELEMENT_RANGE
for y in ELEMENT_RANGE]
for row in MATRIX_ROWS:
for matr in izip(repeat(row ), MATRIX_ROWS):
pass

you can bring that down to 138ms.

For the record: the straightforward solution (the original with tuples and
range() factored out)

r = range(26)
for a in r:
for b in r:
for c in r:
for d in r:
matr = ((a,b),(c,d))

takes 478ms. The "improved" variant is evil performance-wise (1598ms):

r = range(26)
for (a,b,c,d) in [(x,y,z,t) for x in r
for y in r
for z in r
for t in r] :
matr = ((a,b),(c,d))

It might be interesting how much this can be improved with 2.4's generator
expressions.

Peter

Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
12713
by: chad | last post by:
I am writing a program to do some reliability calculations that require several nested for-loops. However, I believe that as the models become more complex, the number of required for-loops will increase. Does Python have a limit on the number of nested for-loops? Thanks.
0
1769
by: mark | last post by:
My problem is I need to have a "nested" repeater. I have an array which I load into a hashtable - that part works great. I can setup the second repeater to work just fine, as long as it's not nested within the first repeater. If it is nested within the first repeater, I don't get any data. If I put the second repeater as a separate repeater, not nested, it works fine. Here's my actual code, showing data pulled from the array within a...
5
7302
by: Martin Schou | last post by:
Please ignore the extreme simplicity of the task :-) I'm new to C, which explains why I'm doing an exercise like this. In the following tripple nested loop: int digit1 = 1; int digit2 = 0; int digit3 = 0; for( ; digit1 < 5 ; digit1++ ) {
46
9936
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are already in a loop." Then he goes on to portray a contrived example that doesn't tell me under what conditions a nested loop might be favoured as a solution? i.e. what are nested loops useful for? What kinds of algorithms are served by nested loops?...
17
3038
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html Why is C# 500% slower than C++ on Nested Loops ??? Will this problem be solved in the future???
9
2490
by: Javaman59 | last post by:
Using local declarations within a block often makes code more readable, but is it less efficient? eg... void P() { while (...) { int i = ...; bool b = ...; .... } }
2
1912
by: mark | last post by:
(not sure if this is the correct group) My problem is I need to have a "nested" repeater. I have an array which I load into a hashtable - that part works great. I can setup the second repeater to work just fine, as long as it's not nested within the first repeater. If it is nested within the first repeater, I don't get any data. If I put the second repeater as a separate repeater, not nested, it works fine. Here's my actual code,...
77
5247
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop. Is this because .NET is inherently slower or does the C# compiler merely produce code that is not as well optimized as the C++ compiler?
5
3124
by: =?Utf-8?B?QUEyZTcyRQ==?= | last post by:
Could someone give me a simple example of nested scope in C#, please? I've searched Google for this but have not come up with anything that makes it clear. I am looking at the ECMA guide and trying to understand Goto in this contect. PS: This is not homework.
8
7264
by: Nathan Sokalski | last post by:
I have several nested For loops, as follows: For a As Integer = 0 To 255 For b As Integer = 0 To 255 For c As Integer = 0 To 255 If <Boolean ExpressionThen <My CodeElse Exit For Next If Not <Boolean ExpressionThen Exit For Next If Not <Boolean ExpressionThen Exit For
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9420
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10205
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10035
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8863
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3556
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2811
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.