Question on if, while, for
Hans Kristian Ruud
hans at inenco.no
Wed Feb 20 10:31:44 EST 2002
Paul Rubin wrote:
> c at tech.usd253.org (Fred) writes:
> > I have written a simple program that I want to simplify. I used if and
> > elif. But I am sure this can be simplified with for or while. Or what
> > if I wrote a function to do the testing?
> >
> > Please DO NOT re-write this for me I want to figure it out for myself.
> > I would just like to know what is the BEST way to do it:
> >
> > 1) For loop (nested??)
> > 2) While loop
> > 3) Function
> > 4) Leave it alone it's fine??
>
> 5) Try to take a clearer look at the problem you're solving, rather
> than getting wrapped up in the programming details. You're trying to
> reduce a fraction to lowest terms. Never mind programming--how would
> you explain that process to a math student? I don't think you'd do it
> the same way your program does it. Try to make your program more
> closely follow the methods you'd learn in a math class for reducing
> fractions. Only after you understand the math should you try to
> express it as Python code.
>
> I'll give a hint: you'll want to know how to compute the least common
> denominator of two integers a and b. You might want to look in a book
> to find out how to do that.
And to spoil all the fun, here is a solution
>>> def gcd(a, b):
... while a > 0:
... print 'a = %d, b = %d' % (a, b)
... rest = b % a
... b = a
... a = rest
... return b
...
>>> gcd(4, 6)
a = 4, b = 6
a = 2, b = 4
2
- hans kristian -
More information about the Python-list
mailing list