Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find fibonacci series upto n using lambda in Python
A Fibonacci series is a widely known mathematical sequence that explains many natural phenomena. It starts with 0 and 1, then each subsequent term is the sum of the two preceding terms. In this article, we will see how to generate a given number of Fibonacci terms using lambda functions in Python.
Method 1: Using map() with Lambda
We use the map() function to apply a lambda function that adds the sum of the last two terms to our list. The any() function is used to execute the map operation ?
Example
def fibonacci(count):
fib_list = [0, 1]
any(map(lambda _: fib_list.append(sum(fib_list[-2:])),
range(2, count)))
return fib_list[:count]
print(fibonacci(8))
print(fibonacci(5))
The output of the above code is ?
[0, 1, 1, 2, 3, 5, 8, 13] [0, 1, 1, 2, 3]
Method 2: Using reduce() with Lambda
The reduce() function applies a lambda function cumulatively to build the Fibonacci sequence. This approach uses functional programming principles ?
Example
from functools import reduce
fib_numbers = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]],
range(n - 2), [0, 1])
print(fib_numbers(8))
print(fib_numbers(10))
The output of the above code is ?
[0, 1, 1, 2, 3, 5, 8, 13] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
How It Works
Both methods use lambda functions to generate Fibonacci numbers:
-
Method 1: Uses
map()withany()to repeatedly append new terms -
Method 2: Uses
reduce()to build the sequence step by step
Comparison
| Method | Function Used | Readability | Performance |
|---|---|---|---|
| map() + any() | map(), any() | Moderate | Good |
| reduce() | reduce() | Complex | Good |
Conclusion
Both lambda-based approaches effectively generate Fibonacci sequences. The map() method is more readable, while reduce() follows pure functional programming principles. Choose based on your preference for readability versus functional style.
