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.