Python: Create Fibonacci series upto n using Lambda
Python Lambda: Exercise-10 with Solution
Write a Python program to create Fibonacci series up to n using Lambda.
Sample Solution:
Python Code :
# Import the 'reduce' function from the 'functools' module
from functools import reduce
# Define a lambda function 'fib_series' that generates a Fibonacci series up to 'n' elements
# It uses the 'reduce()' function along with a lambda function and an initial list [0, 1] to generate the Fibonacci series
fib_series = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]], range(n - 2), [0, 1])
# Print the Fibonacci series up to 2 elements
print("Fibonacci series upto 2:")
print(fib_series(2))
# Print the Fibonacci series up to 5 elements
print("\nFibonacci series upto 5:")
print(fib_series(5))
# Print the Fibonacci series up to 6 elements
print("\nFibonacci series upto 6:")
print(fib_series(6))
# Print the Fibonacci series up to 9 elements
print("\nFibonacci series upto 9:")
print(fib_series(9))
Sample Output:
Fibonacci series upto 2: [0, 1] Fibonacci series upto 5: [0, 1, 1, 2, 3] Fibonacci series upto 6: [0, 1, 1, 2, 3, 5] Fibonacci series upto 9: [0, 1, 1, 2, 3, 5, 8, 13, 21]
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to check whether a given string is number or not using Lambda.
Next: Write a Python program to find intersection of two given arrays using Lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/lambda/python-lambda-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics