On Thursday June 24 2010 07:31:47 Richard D. Moores wrote:
> My question is how to best exit when the big prime has been found. I
> used a flag (see the highlighted lines 34,40,44), but I seem to
> remember that, though they can work, flags are frowned upon by
> Pythonistas, and should be used only when absolutely necessary. So, is
> one necessary in my script?

I think a good way to exit from deep down in a complicated algorithm is to 
raise an exception:

class FoundPrimeException(Exception):
        def __init__(self, big_p):
                Exception.__init__(self)
                self.prime = big_p

Then you put your lines 33 to 43 between a try:... except construction and 
raise your exception in line 40. In the except ...: block you handle the prime 
that you have found. Here are my proposed modifications to your lines 33 to 
47: 

try:
    for b in range(p-1,0,-1):
        a = p - b
        one_off_big_p = 2**a*3**b
        for x in [one_off_big_p - 1, one_off_big_p + 1]:
            if isPrime(x):
                raise FoundPrimeException(x)
except FoundPrimeException, e:
    big_p = e.big_p
    print("The smaller prime", p, "determined this prime, ")
    print("with", len(str(big_p)), "digits:")
    print(big_p)
    print("a and b were", a, b)

time1 = time()
print("Time was", round((time1-time0),2), "secs")


I hope I didn't break your algorithm; I'm typing this directly into the email 
program. 


Eike.
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to