-1

I want to make a rational number calculator, but I don't know how to neglect some characters. E.g., if the program has to calculate the expression "2/9+9/3" and the answer should be in unsimplified form, how to neglect '/' in the above expression while taking input?

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
  • I don't see the problem here... if you're working with fractional numbers, the division operator / becomes the fraction indicator, i.e. any division is actually conversion to a fraction. – Ian Kemp Mar 18 '09 at 10:51
  • Have a look at the fraction module included in Python 2.6 – Georg Schölly Mar 18 '09 at 12:29

1 Answers1

4

I think you need to define a syntax/parser that knows about rational numbers. For your sample input you would like to end up with a parse tree holding something like this:

   add(rational(2, 9)
       rational(9, 3))

Then you'd write code that knows about the various tricks used when calculating with rationals, so that the code implementing the add operation can, for instance, check for the greatest common divisor of its input arguments, and transform the numbers to be addable.

In this case, it would probably rewrite the arguments to be rational(2, 9) and rational(27, 9), then do the addition, thus ending up with rational(29, 9).

You could have a separate function that does simplification, that can simplify that back down to 3+rational(2, 9).

unwind
  • 391,730
  • 64
  • 469
  • 606