Hackerrank Solution: Map and lambda function in Python

Question: Map and Lambda Function - Hacker Rank (Python Functionals)

Let’s learn some new Python concepts! You have to generate a list of the first N Fibonacci numbers,  being the first number. Then, apply the map function and a lambda expression to cube each Fibonacci number and print the list.

Concept:

Advertisement

The map() function applies a function to every member of an iterable and returns the result. It takes two parameters: first, the function that is to be applied, and second, the iterables.
Let’s say you are given a list of names, and you have to print a list that contains the length of each name.

print (list(map(len, ['Tina', 'Raj', 'Tom'])))  
[4, 3, 3]  

Lambda is a single expression anonymous function often used as an inline function. In simple words, it is a function that has only one line in its body. It proves very handy in functional and GUI programming.

sum = lambda a, b, c: a + b + c
sum(1, 2, 3)
6

Lambda functions cannot use the return statement and can only have a single expression. Unlike def, which creates a function and assigns it a name, lambda creates a function and returns the function itself. Lambda can be used inside lists and dictionaries

Input format:

One line of input: an integer N.

Constraints:

Advertisement

0 <= N <= 15

Output format:

A list on a single line containing the cubes of the first N Fibonacci numbers.

Sample input:

5

Sample output:

[0, 1, 1, 8, 27]

The first 5 fibonacci numbers are [0, 1, 1, 2, 3], and their cubes are [0, 1, 1, 8, 27].

 

Possible solutions

Now we will solve the questions using the possible solutions. The following piece of code is already written for you in the Hacker Rank editor.

cube = lambda x: # complete the lambda function 

def fibonacci(n):
    # return a list of fibonacci numbers

if __name__ == '__main__':
    n = int(input())
    print(list(map(cube, fibonacci(n))))

All we need to do is add our code there to find the cube of the Fibonacci numbers from a given range. We will use the following ways to solve the question.

 

Solution-1: Using Python pow() method

Let us first use a simple power method to find the cube of the number from the Fibonacci series. Let us start our first solution:

# Lambda function to find the cube of function 
cube = lambda x: pow(x,3)


def fibonacci(n):
    # return a list of fibonacci numbers
    lis = [0,1]
    
    # for loop starting from 2
    for i in range(2,n):
        lis.append(lis[i-2] + lis[i-1])
    return(lis[0:n])


if __name__ == '__main__':
    n = int(input())
    print(list(map(cube, fibonacci(n))))

As you can see, we have used the lambda function to find the cube of the numbers and use the for loop to create a Fibonacci series.

Input:

5

Output:

Advertisement
[0, 1, 1, 8, 27]

As you can see, we get the desired output.

 

Solution-2: Using the yield keyword

The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value. Now, we will use the yield keyword to get the cubes of the Fibonacci numbers.

# lambda function to find the cube
cube = lambda x: x ** 3

def fibonacci(n

    # initializing the initial values
    a, b, c = 0, 1, 1
              
    # using for loop
    for i in range(n):
        yield a
        
        # creating facbonacci series
        a, b = b, a + b
              
if __name__ == '__main__':
    n = int(input())
    print(list(map(cube, fibonacci(n))))

Input:

5

Output:

[0, 1, 1, 8, 27]

As you can see, we get the cubes of the Fibonacci series.

 

Solution-3: Using fewer lines

As we know in Python we can use many ways to reduce the length of code by writing different statements in one line. In this solution, we will use the list comprehension method to reduce the length of the program.

Advertisement
# lambda function to find the cube
cube = lambda x: x ** 3

def fibonacci(n):
    
    # creating the list of first two items
    fib = [0, 1]
    
    # using list comprehension
    [fib.append(sum(fib[-2:])) for x in range(n)]
    return fib[:n]
              
if __name__ == '__main__':
    n = int(input())
    print(list(map(cube, fibonacci(n))))

Input:

5

Output:

[0, 1, 1, 8, 27]

As you can see, we were able to print out the cubes of the Fibonacci series.

 

Summary:

In this short article, we solved the map and lambda function question from Hacker Rank. We were able to come up with 3 different types of solutions.

 

References

Python map
Question on Hacker Rank: Map and Lambda Function in Python

 

Related Keywords: map and lambda function hackerrank solution, Python program to print fibonacci series using lambda function, python - How to write the Fibonacci Sequence, Print Fibonacci Series using lambda and map or reduce, Map and lambda function in python

Advertisement

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

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 either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X