Hướng dẫn python simplify fraction
still learning Python so any help is welcome. I have written a funtion to get a fraction, but more often than not the fraction can be simplified. My code does not do this yet. Any ideas how to simplify the fraction without using any
example: Any help is welcome!
Tom 7,5712 gold badges14 silver badges30 bronze badges asked Nov 20, 2020 at 14:38
A pretty naive approach to get you started, you can add some checks to make it more efficient.
We use a modulo operator answered Nov 20, 2020 at 14:51
In addition to above answers, if you cannot import any other libraries, here's is the implementation of fractions.gcd for python 2.7 (copied from https://stackoverflow.com/a/11175154/10155740)
so if you'd incorporate this in your code, you should get something like:
answered Nov 20, 2020 at 14:56
QuadUQuadU 3061 silver badge3 bronze badges Here is a solution with a recursive implementation of gcd, using Euclid Algorithm; it also works on negative numbers :
answered Nov 20, 2020 at 14:52
3 You need to divide it by GCD.
answered Nov 20, 2020 at 14:43
EquinoxEquinox 5,9373 gold badges20 silver badges30 bronze badges The naive form of adding two fractions returns a correct answer, just not the most reduced correct answer. For that, you need to divide the numerator and denominator of the result by the greatest
common denominator (GCD) of the original denominators. In this case, the GCD of 2 and 4 is 2, so dividing 6 and 8 by 2 gives the desired answer
though it sounds like you are expected to define your own implementation of
answered Nov 20, 2020 at 14:42
chepnerchepner 458k66 gold badges482 silver badges623 bronze badges 3 Not the answer you're looking for? Browse other questions tagged python function fractions simplify or ask your own question. |