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
: Returnsx
whenx
is less than or equal to 1 -
else fib(x-1) + fib(x-2)
: For other cases, returnsfib(x-1) + fib(x-2)
By using a lambda function, you can implement the Fibonacci sequence with more concise code.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.