lunes, 24 de abril de 2017

Quiz 8 (Fibonacci)

The task:

  • Write a function that calculates returns the “nth” Fibonacci number where we define a function over the Fibonacci numbers mapping the naturals (starting with zero) to the Fibonacci series. So fibonacci(0) returns 0, fibonacci(1) returns 1, fibonacci(2) returns 1 and so on. Note that we are using the modern definition where the sequence starts with zero. You should try to implement this with two solutions: one with a loop and one with recursion. Which do you think is “better”, which looks more “elegant”, which is more “efficient”?
(Here´s a link to know what a fibonacci series looks like: https://en.wikipedia.org/wiki/Fibonacci_number)

So first let's go to the recursion solution, which in my opinion, is the easiest:




Here´s the code: 

def fib(x):
    if x==0:
        return 0
    elif x==1:
        return 1
    else:
        return fib(x-1)+fib(x-2)

x=int(input("Write a number:"))
print ("The fibonacci is:", fib(x))



Now let´s go to the Looping solution:


Here´s the code for the loop method:

def fib(x):
    if x==0:
        return 0
    if x==1:
        return 1
    a=0
    b=1
    for counter in range(x-1):
        c=a+b
        a=b
        b=c
    return c

x=int(input("Write a number:"))
print ("The fibonacci is:", fib(x))

No hay comentarios:

Publicar un comentario