Map & Lambda Using Together | How to cubed Fibonacci series list | HackerRank, Python FunctionTools

admin
By -
0
In this problems we just need to  generate fibonacci  series list elements and using lambda we just each elements to  cubed if you  know  math means multiple them into  3 times and using map combine this two  function and it give and list  of fibonacci  series items  cubed with  size of n.



In this problem we learn how to  use lambda and map together

Code:
'''
1. Define a lambda function called 'cube' that takes an input x and returns x raised to the power of 3.
2. Create a function 'fibonacci(n)' to generate the first n Fibonacci numbers:
    - Initialize the first two numbers in the sequence, a = 0 and b = 1.
    - Use a loop to generate the sequence and store the numbers in a list.
    - In each iteration, append the current value of a to the list and update a and b to the next two Fibonacci numbers.
3. In the main block:
    - Get an integer input from the user that specifies how many Fibonacci numbers to generate.
    - Use the map function to apply the 'cube' function to each number in the generated Fibonacci sequence.
    - Print the list of cubed Fibonacci numbers.
   
Example:
Input: 5

Sample Output:
[0, 1, 1, 8, 27]

Explanation:
The first 5 Fibonacci numbers are: [0, 1, 1, 2, 3]
Their cubes are: [0, 1, 1, 8, 27]
'''

cube = lambda x:x**3 # complete the lambda function

def fibonacci(n):
    a,b = 0 ,1
    lst = []
    for i in range(0,n):
        lst.append(a)
        a, b = b, a+b
    return lst
   
    # return a list of fibonacci numbers

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





Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*