473,387 Members | 1,455 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

breaking out of nested loop

rbt
What is the appropriate way to break out of this while loop if the for
loop finds a match?

while 1:
for x in xrange(len(group)):
try:
mix = random.sample(group, x)
make_string = ''.join(mix)
n = md5.new(make_string)
match = n.hexdigest()
if match == target:
print "Collision!!!"
print make_string
Stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime())
print "Stop", Stop
break
else:
continue
except Exception, e:
print e
Jul 21 '05 #1
9 4991
You either need to set a marker flag with multiple breaks - *or*
(probably more pythonic) wrap it in a try..except and raise an
exception. Define your own exception class and just trap for that if
you want to avoid catching other exceptions.

There is no single command to break out of multiple loops.

Regards,

Fuzzy
http://www.voidspace.org.uk/python

Jul 21 '05 #2
rbt wrote:
What is the appropriate way to break out of this while loop if the for
loop finds a match?
Define a flag first:

keepGoing = True
while 1: while keepGoing:
for x in xrange(len(group)):
try: .... if match == target:
print "Collision!!!"
print make_string
Set the flag here, then do the break:
keepGoing = False
break


Tada...

-Peter
Jul 21 '05 #3
rbt
Thanks guys... that works great. Now I understand why sometimes logic
such as 'while not true' is used ;)

On Tue, 2005-07-12 at 10:51 -0400, Peter Hansen wrote:
rbt wrote:
What is the appropriate way to break out of this while loop if the for
loop finds a match?


Define a flag first:

keepGoing = True
while 1:

while keepGoing:
for x in xrange(len(group)):
try:

...
if match == target:
print "Collision!!!"
print make_string


Set the flag here, then do the break:
keepGoing = False
break


Tada...

-Peter


Jul 21 '05 #4
rbt wrote:
What is the appropriate way to break out of this while loop if the for
loop finds a match?

while 1:
for x in xrange(len(group)):


another option not yet suggested is simply to collapse the two loops into a
single loop:

import itertools

for x in itertools.cycle(range(len(group)):
... as before ...
Jul 21 '05 #5
On Tue, 12 Jul 2005 10:19:04 -0400, rbt wrote:
What is the appropriate way to break out of this while loop if the for
loop finds a match?


Refactor it into something easier to comprehend?

And comments never go astray.
(Untested. And my docstrings are obviously bogus.)

def make_one_thing(group, x):
"""Makes a thing by plonking the frobber.
Expects group to be a list of foo and x to be an index.
"""
mix = random.sample(group, x)
make_string = ''.join(mix)
n = md5.new(make_string)
match = n.hexdigest()
return match

def group_matches(group, target):
"""Cycles over a group of foos, plonking the frobber of each
item in turn, and stopping when one equals target.
"""
for x in xrange(len(group)):
try:
match = make_one_thing(group, x)
if match == target:
return True
except Exception, e:
# don't stop just because the program has a bug
print e
# if we get here, there was no successful match after the
# entire for loop
return False

def test_until_success:
"""Loop forever, or until success, whichever comes first.
"""
group = [1, 2, 3, 4]
target = 5
flag = False
while not flag:
print "No matches yet, starting to search..."
flag = group_matches(group, target)
# if we ever get here, it means we found a collision, and
# flag became True, so the while loop just dropped out
print "Collision!!!"
stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime())
print "Stopped at", stop

--
Steven.
Jul 21 '05 #6
rbt wrote:
What is the appropriate way to break out of this while loop if the for
loop finds a match?


queue discussion why Python doesn't have a "break N" statement...

--
Jeremy Sanders
http://www.jeremysanders.net/
Jul 21 '05 #7
"rbt" <rb*@athop1.ath.vt.edu> wrote in message
news:ma***************************************@pyt hon.org...
What is the appropriate way to break out of this while loop if the for
loop finds a match?


Make it a function and use a "return" statement to break out.
Jul 21 '05 #8
On Tue, 12 Jul 2005 10:19:04 -0400, rbt <rb*@athop1.ath.vt.edu>
declaimed the following in comp.lang.python:
What is the appropriate way to break out of this while loop if the for
loop finds a match?
Uh... test for a match ON the while? (Your indentation is also
incorrect).

NoMatch = True #<<<<<<<<<<
while NoMatch: #<<<<<<<<<<
for x in xrange(len(group)):
try:
mix = random.sample(group, x)
make_string = ''.join(mix)
n = md5.new(make_string)
match = n.hexdigest()
if match == target:
NoMatch = False #<<<<<<<<<<<
Stop = time.strftime("%H:%M:%S-%m-%d-%y",
time.localtime())
print "Collisiion"
print make_string
print Stop
break
except Exception, e:
print e

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 21 '05 #9
[rbt]
What is the appropriate way to break out of this while loop if the for
loop finds a match?

while 1:
for x in xrange(len(group)):
try:
mix = random.sample(group, x)
make_string = ''.join(mix)
n = md5.new(make_string)
match = n.hexdigest()
if match == target:
print "Collision!!!"
print make_string
Stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime())
print "Stop", Stop
break
else:
continue
except Exception, e:
print e


I would wrap the whole thing in a function definition. When you find a
match, just return from the function. Besides cleanly exiting from
multiple loops, the function approach usually leads to better factoring
(in this case, segregating the search logic from everything else).
Raymond

Jul 21 '05 #10

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

Similar topics

3
by: Dennis M. Marks | last post by:
I have a 3 level array. First level is a list of trains. Second level are items about the train. Third level is where there are multiples of the second level item. The search will be of myArray...
5
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;...
46
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...
17
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...
9
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 = ...; .... } }
5
by: Uday Deo | last post by:
Hi everyone, I am looping through 4 nested loops and I would like to break in the inner most loop on certain condition and get the control on the 2 nd loop instead of 3rd loop. Here is briefly...
77
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....
5
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...
8
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.