1 min to read
Reduce Functions - HackerRank Solution Python
Reduce Functions is the medium-level problem of Python on Hackerrank that requires knowledge of the reduce
function in Python. In this post, you will learn how to solve Hackerrank’s Reduce Functions problem and its solution in Python.
Problem Statement and Explanation
Reduce
is a really useful function for performing some computation on a list and returning the result. It applies a rolling computation to sequential pairs of values in a list. For example, reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
calculates ((((1 + 2) + 3) + 4) + 5)
and returns 15
.
Reduce Function in Python
Explanation of Solution
- This code first imports the
Fraction
class from thefractions
module. This class represents a fraction in Python. - The
functools.reduce()
function is used to reduce the list of fractions to a single fraction by multiplying them together. The*
operator is used to multiply two fractions. - The
main()
function first reads the number of fractions from the user. - Then, it reads the numerator and denominator of each fraction from the user and creates a
Fraction
object for each fraction. - Finally, it calls the
product()
function to multiply the fractions and prints the result.
Do share this post with your friends to help us spread the word.