[Tutor] Re: Tutor digest, Vol 1 #763 - 13 msgs

Lance E Sloan lsloan@umich.edu
Thu, 03 May 2001 08:41:42 -0400


"Julieta Rangel" <julieta_rangel@hotmail.com> wrote:
> problem is representing rational numbers, ie,(7/2).  Because my result of 
> this division is not an integer, I don't want Python to divide.  I want 
> (3/3) to be divided, (4/1) to be divided, but I want (7/2) to be left alone. 
> How can I do this?  Can anyone help?

Instead of letting Python divide those numbers, you could store them in
a tuple, (numerator, denominator).  Of course, reduce the fraction
first before storing it in the tuple.  I suppose that instead of
storing fractions with one as the denominator, (n, 1), in a tuple, you
could just store them as the number itself.  That's optional.

Either way, if you have a function that prints the polynomial, you
could make it work with the original or integrated versions, just by
checking the type of coefficient.  Here's what I would do:

	if (type(coeff[i]) == types.TupleType):
		(num, den) = coeff[i]
		if (den == 1):
			print num
		else:
			print '%d/%d' % (num, den)
	else:
		print coeff[i]

Of course, making or finding a rational number class, as Ms. King
suggested, would probably be best.

--
Lance E Sloan
Web Services, Univ. of Michigan: Full-service Web and database design,
development, and hosting.  Specializing in Perl & Python CGIs.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"