Python Newbie

Chris Angelico rosuav at gmail.com
Sun Feb 24 17:08:34 EST 2013


On Mon, Feb 25, 2013 at 8:35 AM, Joshua Landau
<joshua.landau.ws at gmail.com> wrote:
> def solve_quadratic(a, b, c):
> """Solve a quadratic equation of the form ax² + bx + c = 0
>
> The result will be a tuple of the two results; the results can be equal if
> the determinant is 0.
> This supports imaginary results for if the determinant is negative."""
> ...
> results = [top/(2*a) for top in fraction_tops]

Yeah, I think we know which one is the more readable... Just to
nit-pick a little though, that returns a list when its docstring says
it'll return a tuple :)

Other than that (which is probably better solved by changing the docs
than the code), the only change I'd make would be to ditch the
fraction_tops temporary (and to throw out some of the comments that
serve only to reexpress the code that immediately follows them, though
for a demo they're entirely appropriate). Even in a language with
mandatory declarations, the code would look pretty similar:

# Assume that the declaration 'complex' permits a float - otherwise
you need a Pike-style piped declaration eg "float|complex"
# Details elided for brevity, keep the docstring and comments from the
above version
list(complex) solve_quadratic(float a, float b, float c):
	float determinant = b**2 - 4*a*c
	complex sqrt_determinant = determinant ** 0.5
	tuple(complex) squareroots = sqrt_determinant, -sqrt_determinant
	return [(-b + d)/(2*a) for top in squareroots]

Variable names seldom if ever need to identify their types, if by
"type" you mean what the language sees as a type. There are times when
it's useful to adorn a variable name with a unit, perhaps (length_ft
and height_m shouldn't be multiplied together), or some other special
marker (a "tainted" flag on all data that's come from user input, and
which therefore must not be executed or interpolated into SQL or
anything), but this is a much higher level of abstraction.

ChrisA



More information about the Python-list mailing list