HackerRank Solution: Python Reduce Function [3 Methods]


Written by - Bashir Alam
Reviewed by - Deepak Prasad

Question: Reduce Function - Hacker Rank (Python Functionals)

Given a list of rational numbers, find their product.

Concept:

The reduce() function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3] and you have to find its sum.

reduce(lambda x, y : x + y,[1,2,3])
6

You can also define an initial value. If it is specified, the function will assume the initial value as the value given, and then reduce. It is equivalent to adding the initial value at the beginning of the list. For example:

reduce(lambda x, y : x + y, [1,2,3], -3)
3

from fractions import gcd
reduce(gcd, [2,4,8], 3)
1

Input format:

The first line contains n, the number of rational numbers.
The ith of the next n lines contains two integers each, the numerator( Ni ) and denominator( Di ) of the ith rational number in the list.

Constraints:

  • 1 <= n <= 100
  • 1 <= Ni, Di <= 109

Output format:

Print only one line containing the numerator and denominator of the product of the numbers in the list in its simplest form, i.e. numerator and denominator have no common divisor other than 1.

Sample input:

3
1 2
3 4
10 6

Sample output:

5 8

 

Possible solutions:

Now we will go through multiple solutions to solve the given question. The following code is already given in the Hacker Rank code editor:

from fractions import Fraction
from functools import reduce

def product(fracs):
    t = # complete this line with a reduce statement
    return t.numerator, t.denominator

if __name__ == '__main__':
    fracs = []
    for _ in range(int(input())):
        fracs.append(Fraction(*map(int, input().split())))
    result = product(fracs)
    print(*result)

As you can see, we have to complete the product() function and add a reduce() method there. In this section, we will use the following different methods to solve the question.

  • Using Simple way
  • Using for loop
  • Using math module

 

Solution-1: Simple way

Now let us use the lambda function inside the reduce() method to get the required results.  We will first import the required modules as shown below:

# importing the functions
from fractions import Fraction
from functools import reduce


# defining the function
def product(fracs):
    
    # using the reduce() method with lambda
    t = Fraction(reduce(lambda x, y: x * y, fracs))
    return t.numerator, t.denominator

# the main function
if __name__ == '__main__':
    fracs = []
    for _ in range(int(input())):
        fracs.append(Fraction(*map(int, input().split())))
    result = product(fracs)
    print(*result)

Input:

3
1 2
3 4
10 6

Output:

5 8

As you can see, the above code is perfectly working and we get the desired output.

 

Solution-2: Using for loop

Another way is to use a for loop inside the function that will iterate and append the denominator and numerator in a list and then use the reduce and lambda function as we used in the above solution

# importing the functions
from fractions import Fraction
from functools import reduce

# the function
def product(fracs):
    
    # creating empty list
    total = []
    
    # for loop to append numerator and denominator in list
    for frac in fracs:
        t = Fraction(frac.numerator, frac.denominator)
        total.append(t)
        
    # using lambda and reduce function
    res = reduce(lambda x,y : x*y, total)
    return res.numerator, res.denominator
    return t.numerator, t.denominator

if __name__ == '__main__':
    fracs = []
    for _ in range(int(input())):
        fracs.append(Fraction(*map(int, input().split())))
    result = product(fracs)
    print(*result)

Input:

3
1 2
3 4
10 6

Output:

5 8

As you can see, we get the desired output:

 

Solution-3: Using math module

This time we will use the math module to check and check if the common divisor of the two integers is 1 or not. The math.gcd() method returns the greatest common divisor of the two integers. Lets start the coding part.

# importing the modules
from fractions import Fraction
from functools import reduce
import math

# creating function
def product(fracs):
    
    # using lamda and reduce functions
    t =reduce(lambda x,y: x*y,fracs)

    # using if statement to print the denominator and numerator
    if math.gcd(t.numerator, t.denominator) == 1:

        return t.numerator, t.denominator

if __name__ == '__main__':
    fracs = []
    for _ in range(int(input())):
        fracs.append(Fraction(*map(int, input().split())))
    result = product(fracs)
    print(*result)

Input:

3
1 2
3 4
10 6

Output:

5 8

As you can see, the above code returns the desired output.

 

Summary

In this short article, we come up with multiple solutions to solve the reduce function question on Hacker Rank. We use a simple way, python loops, and a python math module to solve the question.

 

References

Python math module
Question on the Hacker Rank: Reduce Function in Python

 

Related keywords: reduce function in python hackerrank solution, reduce function in python3 hackerrank solution, reduce function in python

 

Views: 16

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment