- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find fibonacci series upto n using lambda in Python
A fibinacci series is a widley known mathematical series that explains many natural phenomenon. It starts with 0 and 1 and then goes on adding a term to its previous term to get the next term. In this article we will see how to generate a given number of elements of the Fibonacci series by using the lambda function in python.
With sum and map
We use the map function to apply the lambda function to each element of the list. We design a list slicing mechanism to get sum of previous two terms and use range to keep count of how many terms we are going to generate.
Example
def fibonacci(count): listA = [0, 1] any(map(lambda _:listA.append(sum(listA[-2:])), range(2, count))) return listA[:count] print(fibonacci(8))
Output
Running the above code gives us the following result −
[0, 1, 1, 2, 3, 5, 8, 13]
With reduce function
In this approach we use the reduce function along with the lambda function to get the sum of previous two terms. We have to apply lambda twice along with range to keep count of number of terms required and get the final result.
Example
from functools import reduce fib_numbers = lambda y: reduce(lambda x, _: x + [x[-1] + x[-2]], range(y - 2), [0, 1]) print(fib_numbers(8))
Output
Running the above code gives us the following result −
[0, 1, 1, 2, 3, 5, 8, 13]
- Related Articles
- How to implement the Fibonacci series using lambda expression in Java?
- Python Program to Find the Fibonacci Series Using Recursion
- Python Program to Find the Fibonacci Series without Using Recursion
- Find sum of the series ?3 + ?12 +.... upto N terms in C++
- Find sum of the series 1+22+333+4444+... upto n terms in C++
- Java Program to Find Even Sum of Fibonacci Series till number N
- Fibonacci series program in Java using recursion.
- Sum of the series 0.7, 0.77, 0.777 … upto n terms in C++
- Fibonacci series program in Java without using recursion.
- Program to find Fibonacci series results up to nth term in Python
- C++ Program to find the sum of the series 23+ 45+ 75+….. upto N terms
- N-th Fibonacci number in Python Program
- Find Sum of Series 1^2 - 2^2 + 3^2 - 4^2 ... upto n terms in C++
- Fibonacci Series in C#
- Generate Fibonacci Series
