Guidelines

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: Returns x when x is less than or equal to 1

  • else fib(x-1) + fib(x-2): For other cases, returns fib(x-1) + fib(x-2)

By using a lambda function, you can implement the Fibonacci sequence with more concise code.

Mission
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

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result