Wednesday, January 05, 2022

Fibonacci One Line Code with Python

Fibonacci One Line Code with Python



This is using recursive and shorthand if to implement fibonacci. Fibonacci is a sequence, the value of the sequence is the sum of the previous 2 numbers in the sequence: eg. 1, 1, 2, 3, 5, 8, 13, 21, ...

The normal Python function:

  def fibonacci(n):
	return 1 if n<=1 else fibonacci(n-1) + fibonacci(n-2)
  

To output:

    for n in range(8):
        print(fibonacci(n))
  

Ok, with the function define, that's 2 lines of code.

No comments: