Lecture
Calculating Fibonacci Sequence Using Lambda Functions
You can calculate the Fibonacci sequence using simple logic and recursion with lambda functions.
The Fibonacci sequence is a sequence where each number is the sum of the two preceding ones, starting from 0 and 1, following the pattern 0, 1, 1, 2, 3, 5, 8....
Implementing with Lambda Functions
You can recursively calculate the Fibonacci sequence using a lambda expression as shown below.
Lambda function for Fibonacci sequence
# Lambda function to calculate Fibonacci sequence fib = lambda x: x if x <= 1 else fib(x-1) + fib(x-2) # 5 (5th value in 0, 1, 1, 2, 3, 5) print(fib(5)) # 55 print(fib(10))
The fib lambda function in the code operates as follows:
-
x if x <= 1: Returnsxwhenxis less than or equal to 1 -
else fib(x-1) + fib(x-2): For other cases, returnsfib(x-1) + fib(x-2)
Using a lambda function allows you to implement the Fibonacci sequence in a concise, single-line expression.
Previous lessonCreating Concise Anonymous Functions with LambdaNext lessonCoding Quiz - Extract Elements from List
Lessons in this chapter · Recursive and Lambda Functions
- 1. Functions That Call Themselves - Recursive Functions
- 2. Comparing Loop and Recursive Functions
- 3. Enhancing Recursive Function Efficiency with Memoization
- 4. Handling UnboundLocalError in Recursion
- 5. Multiple-choice quiz
- 6. Using Functions and Tuples Together
- 7. Functions within Functions - Callback Functions
- 8. Processing Sequences with filter() and map() Functions
- 9. Multiple-choice quiz
- 10. Creating Concise Anonymous Functions with Lambda
- 11. Calculating Fibonacci Sequence Using Lambda Functions
- 12. Coding Quiz - Extract Elements from List
- 13. Multiple-choice quiz
- 14. Fill-in-the-blank quiz
Quiz
0 / 1
What is the most appropriate word for the following blank?
The Fibonacci sequence is a sequence where .
the square of the previous number is the next number
the product of the previous two numbers is the next number
twice the previous number is the next number
the sum of the previous two numbers is the next number
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help