Find fibonacci series upto n using lambda in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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]
raja
Published on 26-Aug-2020 07:42:31
Advertisements