Cecil Westerhof <ce...@decebal.nl> writes: > To show why it is often easy, but wrong to use recursive functions I > wrote the following two Fibonacci functions: > def fib_ite(n): > if not type(n) is int: > raise TypeError(f'Need an integer ({n})') > if n < 0: > raise ValueError(f'Should not be negative ({n})') > > if n in [0, 1]: > return n > > # a is previous fibonacy (starts with fib(0)) > # b is current fibonaccy (starts with fib(1)) > a, b = 0, 1 > # range goes to n - 1, so after loop b contains fib(n) > for i in range(1, n): > a, b = b, a + b > return b > > > def fib_rec(n): > if not type(n) is int: > raise TypeError(f'Need an integer ({n})') > if n < 0: > raise ValueError(f'Should not be negative ({n})') > > if n in [0, 1]: > return n > > return fib_rec(n - 2) + fib_rec(n - 1) > > The first eight lines are the same. And I did change the description > of the errors, which had to be done in both functions. What would be > the best way to circumvent this? > Two options are: > - Call an init function. > - Call the 'master' function with a lambda. > > What is the preferable way, or is there a better way?
I have chosen this implementation with inner functions: def fibonacci(n, implementation = 'iterative'): def ite(n): # a is previous fibonacy (starts with fib(0)) # b is current fibonaccy (starts with fib(1)) a, b = 0, 1 # range goes to n - 1, so after loop b contains fib(n) for i in range(1, n): a, b = b, a + b return b def rec(n): if n in [0, 1]: return n return rec(n - 2) + rec(n - 1) if not type(n) is int: raise TypeError(f'Need an integer ({n})') if n < 0: raise ValueError(f'Should not be negative ({n})') if n in [0, 1]: return n if implementation == 'iterative': return ite(n) elif implementation == 'recursive': return rec(n) raise ValueError(f'Got a wrong function implementation type: {type}') -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list