- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to find product of rational numbers using reduce function
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)
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))
- Python Program to Find the Product of two Numbers Using Recursion
- Java Program to Find the Product of Two Numbers Using Recursion
- Golang Program to Find the Product of Two Numbers Using Recursion
- C++ Program to Find the Product of Two Numbers Using Recursion
- How do we find the product of two rational numbers?
- Program to find minimum numbers of function calls to make target array using Python
- C program to find GCD of numbers using recursive function
- Program to find product of few numbers whose sum is given in Python
- C program to find GCD of numbers using non-recursive function
- Program to find sign of the product of an array using Python
- The product of two rational numbers is 15. If one of the numbers is $-10$, find the other.
- Find the Number Occurring Odd Number of Times using Lambda expression and reduce function in Python
- How to find the product of two binary numbers using C#?
- Python program to find Cartesian product of two lists
- Python Rational numbers (fractions)