Python program to find product of rational numbers using reduce function

PythonServer Side ProgrammingProgramming

Suppose we have a list of rational numbers. We have to find their product using reduce function. The reduce() function applies a function with two arguments cumulatively on a list of objects from left to right.

So, if the input is like fractions = [(5,3),(2,8),(6,9),(5,12),(7,2)], then the output will be (175, 432) because 5/3 * 2/8 * 6/9 * 5/12 * 7/2 = (5*2*6*5*7)/(3*8*9*12*2) = 2100/5184 = 175/432.

To solve this, we will follow these steps −

  • fracs := a new list
  • for each f in frac, do
    • insert a new fraction object from (numerator, denominator) pair f at the end of fracs
  • t := reduce(fracs with function func(x, y) returns x*y)
  • return pair of (numerator of t, denominator of t)

Example

Let us see the following implementation to get better understanding

from fractions import Fraction
from functools import reduce

def solve(frac):
   fracs = []
   for f in frac:
      fracs.append(Fraction(*f))

   t = reduce(lambda x, y: x*y, fracs)
   return t.numerator, t.denominator

frac = [(5,3),(2,8),(6,9),(5,12),(7,2)]
print(solve(frac))

Input

[(5,3),(2,8),(6,9),(5,12),(7,2)]

Output

(175, 432)
raja
Published on 12-Oct-2021 08:56:49
Advertisements