#!/usr/bin/env python3
# https://onlinegdb.com/rJBk6uW88
# https://stackoverflow.com/questions/60673175
# You can copy or edit this example
# To run it clic `Execute` above left
# Click in STDIN to define the input
# A fixed version of the original code
# This function returns the last term only
def fib1(n):
n = int(n)
if n == 0 or n == 1: # Only add n==1
return 1
return fib1(n - 1) + fib1(n - 2)
# Trying to print the sequence
# Bad code
def fib2(n):
n = int(n)
if n == 0 or n == 1:
print(1, end=", ")
return 1
a = fib2(n - 1)
b = fib2(n - 2)
print(a+b, end=", ")
return a+b
# A version using a loop to generate all terms
# This code returns a list of terms
def fib3(n):
n=int(n)
terms = []
i=0
while i<=n:
if i==0 or i==1:
terms.append(1)
else:
terms.append(terms[-2]+terms[-1])
i+=1
return terms
# Trying to generate the sequence using a recursive code
# NOT FINISH
def fib4(p):
if isinstance(p, list):
n = p[-1] # Last element
else:
n = int(p)
p = [] # The list to populate in the loop
if n == 0 or n == 1:
return p.append(1)
else:
aux = fib3(n-1)[0] + fib3(n-2)[0]
return p.append(aux)
num = input("Give me a number: ")
print()
print("\nUssing fib1: Recurcive. Only last term")
print(fib1(num))
print("\nUssing fib2: Recurcive. Trying to print all terms")
print(fib2(num))
print("\nUssing fib3: With loops. Printing all terms")
list_of_terms = fib3(num)
print(list_of_terms)
#print("Ussing fib4:")
#list_of_terms = fib4(num)
#print(list_of_terms)