[Tutor] A better way for greatest common divisor
smokefloat at gmail.com
Sat Jul 31 06:37:49 CEST 2010
On Fri, Jul 30, 2010 at 11:51 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, 31 Jul 2010 01:03:27 pm David Hutto wrote:
>> This fixes the floating point 'bug' when numerator is greater than
>> denominator: http://python.pastebin.com/bJ5UzsBE
> I don't mean to be disparaging ... ah hell, who am I fooling? Yes I do.
> What is that mess? *wink*
It works except under , and that's fixable. And even, I know it's a
good gradumacated the eighth grade, newbie attempt.*winks* back.
> I can see at least four problems with that:
> 1. You have a function called "gcd" that doesn't calculate the gcd, but
> does something else as well. That makes it a misleading name.
I still have the habit of wanting to use the functions like I would an
instance of the functions.
> 2. The principles of code reuse and encapsulation suggest that each
> function should (as much as possible) do one thing, and do it well. You
> have a function that tries to do two or three things. You should have a
> single function to calculate the gcd, and a second function to use the
> gcd for reducing a fraction as needed, and potentially a third function
> to report the results to the user.
Then maybe I should have done a larger class of functions instead then?
> 3. Your function has a serious bug. To see it, call gcd(5, 5) and see
> what it doesn't do.
I'll get to it, but it seems like I had that in the original, not the
revised, maybe not, but did all other test cases for it, other than
> 4. Code duplication. Your function repeats fairly major chunks of code.
> Copy-and-paste programming is one of the Deadly Sins for programmers.
> The way to get rid of that is by encapsulating code in functions (see
> point 1 above).
I thought about putting certain print statements in a function, as
well as seperating the gcd into a from fractions import *, with a
different parameter for each if the returning if placed it into the
called function, but it seemed a little *overkill*, when it worked
well within the single function, with a few parameters placed in
through an instance with input.
> Steven D'Aprano
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
More information about the Tutor