[Edu-sig] Algebra 2
Andre Roberge
andre.roberge at gmail.com
Sat Oct 4 03:51:03 CEST 2008
2008/10/3 michel paul <mpaul213 at gmail.com>:
[SNIP]
>
> Here's the same solution in Python:
>
> x0, y0 = input('Enter x0, y0 --->')
> x1, y1 = input('Enter x1, y1 --->')
> rise = y1 - y0
> run = x1 - x0
> if rise == 0: print 'y =', y0
> elif run == 0: print 'x =', x0
> else:
> m = rise/run
> b = y0 - m*x0
> print 'y =', m, 'x +', b
>
I find that this (and even more so for the other solutions below) not
as readable as it should be. For me, if/elif/else really gain from
being indented, and blank lines can also add to divide the program
into "functional unit". So I would write instead:
x0, y0 = input('Enter x0, y0 ---> ')
x1, y1 = input('Enter x1, y1 ---> ')
rise = y1 - y0
run = x1 - x0
if rise == 0:
print 'y =', y0
elif run == 0:
print 'x =', x0
else:
m = float(rise)/run # avoid dividing two integers ...
b = y0 - m*x0
print "y = %f x + %f" % (m, b)
with perhaps some thoughts given to having a set number of decimal
places for the floats.
Just a thought...
André
> You can see the same logic, but it's a bit shorter. That's because there's
> no use of GOTO. The elimination of GOTO was one of the important features
> in the development of PASCAL, and ever since those days GOTO has been
> considered bad style. It produces crazy and cumbersome code. Functional
> organization is far superior.
>
> You can see that the Python version is just as easy to read, or easier, than
> the BASIC. So, you can use Python in this simple procedural sort of way.
> However, Python supports various paradigms, so you can also organize things
> functionally:
>
> def slope_intercept(A, B):
> x0, y0 = A
> x1, y1 = B
> rise, run = y1 - y0, x1 - x0
> if run == 0: return None, x0
> m = rise/run; b = y0 - m*x0
> return m, b
>
> And even here, the code is longer than it needs to be. You can cut it down
> to:
>
> def slope_intercept(A, B):
> rise, run = A[1] - B[1], A[0] - B[0]
> if run == 0: return None, A[0]
> return rise/run, A[1] - rise/run*A[0]
>
> And you can even cut it down more, but that's not the point.
>
> This accomplishes the same thing as the original, just without printing the
> equations. You would then call this function to obtain the values of m and
> b for printing, if that's what you wanted to do, or, you could chain this
> function together with other functions to construct something more complex.
> It's what functional analysis is all about. You consider I/O stuff
> decoration. It's not the important part mathematically speaking.
>
> Functional decomposition of tasks ---> sure sounds like Analysis to me! :
> ) Isn't it essentially the same kind of thinking?
> _______________________________________________
> Edu-sig mailing list
> Edu-sig at python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>
>
More information about the Edu-sig
mailing list