Python indentation deters newbies?
Tim Hochberg
tim.hochberg at ieee.org
Tue Aug 17 17:48:52 CEST 2004
Jeff Shannon wrote:
> beliavsky at aol.com wrote:
>
>> You may want to exit a nested loop when testing if a condition involving
>> several variables is met, such as searching for a zero of a multivariate
>> function.
>> In Python you can print i,j,k and exit() when m == 0, but in a larger
>> program
>> you may want more control.
>>
>>
>
> In this case, I can see several Pythonic ways of doing this.
>
> One would be to use an exception. While exceptions are not considered
> good control structures in other languages, they *are* considered
> acceptable (and even desirable) in Python.
>
> Another way would be to wrap the nested loops inside a function, and
> simply return the appropriate triple from that function as soon as you
> find it.
>
> An improvement on that would be to replace your return statement with a
> yield. Suddenly you've got a generator that'll find a whole series of
> Pythagorean triples!
>
[SNIP perfectly good Pythag. triple generator]
Just for fun, here's one that will spit out as many reduced pythagorean
triples as you care to look at.
-tim
def gcd(a, b):
# Euclidean alg.
assert (b > 0) and (b > 0)
if a < b:
a, b = b, a
while b:
a, b = b, a % b
return a
def rptriples():
"generate reduced pythagorean triples"
# Based on formulae from Mathworld, corrected by one from
# planetMath.
v = 1
while True:
u = 1 + (v%2) # u must be opposite parity from v
while u < v:
if gcd(u,v) == 1:
u2, v2 = u*u, v*v
a, b, c = v2-u2, 2*u*v, u2+v2
if a > b:
a, b = b, a
yield a, b, c
u += 2
v += 1
More information about the Python-list
mailing list