usingMaths.com
Demonstrating and showing pupils and students one application of Mathematics.







<< Previous Next >>

Code for Sorting Fractions in Ascending and Descending Orders in Python



Rationalise (Canonise) the Fractions before Sorting

Before fractions are sorted, they are rationalised; i.e., they are put in a form where their denominators become the same. This same denominator is the LCM of the denominators of all the separate fractions.
After this is done, the new numerators can easily be sorted in a preferred order.


Steps for Sorting of Fractions Python code

The following steps will guide us in writing our code.
Let's illustrate with 5/9, 3/7, 1/2

Step 1:

Find the LCM of the denominators.
         ⇒ LCM of 9, 7 & 2 = 126

Step 2:

In a turn by turn fashion, divide the found LCM from Step 1 by each denominator, multiplying the quotient by the corresponding numerator.
         ⇒ ((5 x 14), (3 x 18), (1 x 63))/126
         = (70, 54, 63)/126

Step 3:

Go ahead and sort the numerators in our order of choice.
         ⇒ In ascending order:
         54/126, 63/126, 70/126
         = 3/7, 1/2, 5/9


Create a new module file; call it SortFraction.py.
Type out the adjoining Python code for sorting fractions in ascending and descending orders.



Note: You can comment out the SubtractFraction Python object code in the main class from the previous lesson or simply continue from where it stopped.


So!

Feel free to try out your own set of numerators and denominators for fractional sorting.









<< Previous Next >>