Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find product of rational numbers using reduce function
The reduce() function in Python applies a function cumulatively to items in a sequence, reducing them to a single value. When working with rational numbers (fractions), we can use reduce() to find their product efficiently.
For example, if we have fractions = [(5,3),(2,8),(6,9),(5,12),(7,2)], the product will be 5/3 * 2/8 * 6/9 * 5/12 * 7/2 = (5*2*6*5*7)/(3*8*9*12*2) = 2100/5184 = 175/432 (in reduced form).
Syntax
from functools import reduce reduce(function, iterable)
Algorithm Steps
- Create a list of Fraction objects from the input tuples
- Use
reduce()with a lambda function to multiply all fractions - Return the numerator and denominator of the resulting fraction
Example
Here's the implementation using reduce() to find the product of rational numbers ?
from fractions import Fraction
from functools import reduce
def solve(frac):
fractions = []
for f in frac:
fractions.append(Fraction(*f))
result = reduce(lambda x, y: x * y, fractions)
return result.numerator, result.denominator
# Test with sample data
frac = [(5,3), (2,8), (6,9), (5,12), (7,2)]
product = solve(frac)
print(f"Product: {product}")
print(f"As fraction: {product[0]}/{product[1]}")
Product: (175, 432) As fraction: 175/432
Step-by-Step Calculation
Let's trace through the multiplication process ?
from fractions import Fraction
from functools import reduce
def solve_with_steps(frac):
fractions = [Fraction(*f) for f in frac]
print("Fractions:", fractions)
result = reduce(lambda x, y: x * y, fractions)
print(f"Product: {result}")
return result.numerator, result.denominator
frac = [(5,3), (2,8), (6,9), (5,12), (7,2)]
numerator, denominator = solve_with_steps(frac)
print(f"Final result: ({numerator}, {denominator})")
Fractions: [Fraction(5, 3), Fraction(1, 4), Fraction(2, 3), Fraction(5, 12), Fraction(7, 2)] Product: 175/432 Final result: (175, 432)
Alternative Approach
You can also use a more concise version with list comprehension ?
from fractions import Fraction
from functools import reduce
def product_fractions(frac):
return reduce(lambda x, y: x * y, [Fraction(*f) for f in frac])
frac = [(5,3), (2,8), (6,9), (5,12), (7,2)]
result = product_fractions(frac)
print(f"Product: ({result.numerator}, {result.denominator})")
Product: (175, 432)
Conclusion
The reduce() function provides an elegant way to find the product of rational numbers by applying multiplication cumulatively. The Fraction class automatically handles simplification, ensuring the result is in its reduced form.
