How do you reduce a fraction in python?
The Show
There's a recipe over here for a numpy gcd. Which you could then use to divide your fraction CorrectnessYour function reduces Too many special casesYour function distinguishes far too many cases. The process of simplifying a fraction can be reduced to the following 4 steps:
All other checks (if numerator is zero, comparing absolute values, etc) are not necessary and automatically handled by the above algorithm. Computing the "common factor"Your method to compute the common factor of numerator and denominator is
But you don't need all factors, only the largest common one. So it would be faster to start with the largest possible common factor and stop as soon a common factor is found. This would roughly look like:
On my MacBook Pro, this reduces the time to simplify the fraction But you can do much better. The Euclidean algorithm is a well-known, simple and fast algorithm to compute the greatest common divisor of integers, and it is easy to implement. The reduces the time to simplify Putting it all together:There are probably many Python implementations of the Euclidean algorithm, I copied one from https://stackoverflow.com/a/11175154/1187415:
As you can see, dividing the denominator by the common divisor gives a positive result, which means that step #3 it not necessary anymore. This also means that the fraction is already simplified exactly if the common divisor of numerator and denominator is equal to one. So your main method reduces to View Discussion Improve Article Save Article View Discussion Improve Article Save Article Given two integers x and y and where x is divisible by y. It can be represented
in the form of a fraction x/y. The task is to reduce the fraction to its lowest form. Input : x = 16, y = 10 Output : x = 8, y = 5 Input : x = 10, y = 8 Output : x = 5, y = 4 Approach: Both of the values x and y will be divisible by their greatest common divisor. So if we divide x and y from the gcd(x, y) then x and y can be reduced to its simplest form. C++
Java
Python3
C#
PHP
Javascript
Output: x = 8, y = 5 Time Complexity: O(log(max(x,y))) Auxiliary Space: O(log(max(x,y))) Can Python handle fractions?This module provides support for rational number arithmetic. It allows to create a Fraction instance from integers, floats, numbers, decimals and strings. Fraction Instances : A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string.
How do you get a fraction in Python?You have two options:. Use float.as_integer_ratio() : >>> (0.25).as_integer_ratio() (1, 4) (as of Python 3.6, you can do the same with a decimal. Decimal() object.). Use the fractions.Fraction() type: >>> from fractions import Fraction >>> Fraction(0.25) Fraction(1, 4). |