[Tutor] A better way for greatest common divisor

Steven D'Aprano steve at pearwood.info
Sat Jul 31 05:51:55 CEST 2010

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*

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. 

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.

3. Your function has a serious bug. To see it, call gcd(5, 5) and see 
what it doesn't do.

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).

Steven D'Aprano

More information about the Tutor mailing list