DEV Community

Discussion on: Let's Get Clever #1: Fibonacci Sequence

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Here's my own first pass. I love one-liners. (Python 3)

def fib_elem(n, p=(0,1)):
    return fib_elem(n-1, (p[1], sum(p))) if n else p[0]

Unpacking that, the logic is basically:

def fib_elem(n, p=(0,1)):
    if n:
        return fib_elem(n-1, (p[1], sum(p)))
    else:
        return p[0]

My solution is recursive. I start with a pair of numbers (0,1). On each recursive call, I'm generating a new pair such that the old second value is the new first value, and the new second value is the sum of the old pair. On each recursive call, I also pass an n value that is one less.

If n is zero, the conditional statement would fail, and I'd return the first value in the pair instead of doing the next calculation.

I'm aware that this approach would actually generate one more pair than necessary, however, it also allows it to be correct for n=0.