So Iām trying to show that the recursive method to produce a fibonacci number is very inefficient, I'm using a list cause they are called by reference and therefore once the functions split up they still change the same variable. The Problem: i don't know how to clean up the list when we're done. Which leads to the problem that at the first run through our list goes through 1 to 5 which is desired, but starts on the 2nd run through from 6 to 10.
# Iterative method has exactly n repetitions
# let's compare recursive method:
def fiborec(n, i = []):
i.append(len(i)+1)
print('this is call nr.:', len(i))
if n == 0:
return 0
elif(n == 1):
return 1
else:
return fiborec(n - 1, i) + fiborec(n - 2, i)
I also tried:
def fiborec(n, i = [0]):
i[0] += 1
print('this is call nr.:', i[0])
Both methods show the same behaviour :( this leads me to expect that, i = [0]
is not used because a reference already exists.
del i[:]
won't work because there's no definite end since we have two ending conditions, so the place where to add it is somewhat unclear - to me at least.
So... my temporary fix:
def fiborec(n):
"""Docstring: returns Fibonacci Number for given Int.
recursive method
"""
i = [0] # we want i to be "passed by reference" due to lots of function calls
# but also to be resetted should we reuse the function
return _fiborecursion(n, i)
I don't like it but it's the best I can think of right now D: Should anyone have a solution where I don't need two functions please let us know ^_^