Open essepuntato opened 4 years ago
def fib(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def test_fib(n, expected):
result = fib(n)
if result == expected:
return True
else:
return False
print(test_fib(0, 0)) # True
print(test_fib(1, 1)) # True
print(test_fib(2, 1)) # True
print(test_fib(3, 2)) # True
print(test_fib(4, 3)) # True
print(test_fib(5, 5)) # True
print(test_fib(6, 8)) # True
def test_fib(n, expected):
if fib(n) == expected:
return True
else:
return False
def fib(n):
if n <= 0:
return n
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
print(test_fib(7, 13)) # True
def test_fib(n, expected):
result = fib(n)
if result == expected:
return True
else:
return False
def fib(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
print(test_fib(0, 0)) #True
print(test_fib(1, 1)) #True
print(test_fib(2, 1)) #True
print(test_fib(4, 3)) #True
print(test_fib(9, 34)) #True
Hi all,
please find attached my personal solution – also available online:
# Test case for the function
def test_fib(n, expected):
result = fib(n)
if expected == result:
return True
else:
return False
# Code of the function
def fib(n):
if n <= 0:
return 0
if n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
# Tests
print(test_fib(0, 0))
print(test_fib(1, 1))
print(test_fib(2, 1))
print(test_fib(7, 13))
print(test_fib(-15, 0))
@aschimmenti please look again at the definition of Fibonacci, because there is something wrong in your implementation. @elisasilvad please remember that all the tests must pass.
def fib(n):
if n <= 0:
return 0
if n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
fibn = []
requested_number = input("Type the fibonacci number you want: ")
for i in range(int(requested_number)+1):
fibn.append(fib(i))
print(fibn)
def test_fib(n, expected):
result = fib(n)
if result == expected:
return True
else:
return False
print(test_fib(n, expected))
Define a recursive function
def fib(n)
that implements the algorithm to find the nth Fibonacci number. In particular, ifn
is less than or equal to 0, then 0 is returned as a result. Otherwise, ifn
is equal to 1, then 1 is returned. Otherwise, return the sum of the same function called withn-1
andn-2
as input. Please accompany the function with the related test case.