w3resource

Python: Create Fibonacci series upto n using Lambda


10. Fibonacci Series Lambda

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]

For more Practice: Solve these Related Problems:

  • Write a Python program to generate the first n prime numbers using lambda.
  • Write a Python program to generate a modified Fibonacci series where each term is twice the sum of the previous two terms using lambda.
  • Write a Python program to generate a Fibonacci series in reverse order up to n using lambda.
  • Write a Python program to generate a Fibonacci series up to n, including only even numbers, using lambda.

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.



Follow us on Facebook and Twitter for latest update.