I'm working with a basic Python MIT free courseware and I have run into a wall with a recursion exercise. The original program takes an integer and provides its Fibonacci using recursion. The book provides the script for the program, but the subsequent exercise asks to input a way for the program to recognize how many times fib(2) is executed on its way to calculating fib(n). ``
Here is the code:
def fib(n):
"""Assumes n is int > 0
Returns Fibonacci Number of n"""
if n ==0 or n==1:
return n
else:
return fib(n-1) + fib(n-2)
def testfib(n):
for i in range(n+1):
print('fib of', i, 'is ', fib(i))
x=int(input('Enter a number: '))
print('Fibonacci of', x, 'is',fib(x))
print(testfib(x))
There is an answer given in another thread I'm trying to wrap my head around and wondering if someone could explain how, what seems like tuples, in the else portion are serving as variables names in the below code? reference: Trouble adding feature to recursive Fibonacci program
def fib(n):
"""Assumes n is int > 0
Returns the nth Fibonacci number and number of times it was called"""
if n == 0 or n == 1:
return n, 0
else:
f1, count1 = fib(n-1)
f2, count2 = fib(n-2)
sum_counts = count1 + count2
if n == 2:
sum_counts = 1
return f1 + f2, sum_counts
def testfib(n):
for i in range(n+1):
f, count = fib(i)
print('fib of', i, 'is ', f, end="\t")
print('count of fib(2) is ', count)
x = int(input('Enter a number: '))
print('Fibonacci of', x, 'is', fib(x)[0])
print(testfib(x))
fib()function returns a sequence of two items — atuple— and they can be assigned directly into two different variables: i.e.a, b = fib(x). Doing this is called "tuple unpacking".