I was practicing Fibonacci sequence generating in python and following example of memoization from How do I print a fibonacci sequence to the nth number in Python?.
Then I encountered one interesting difference using return one-liner and not. For example, the example code is given below. In the first example, we do not use return one-liner and it runs very fast, however, in the second example we use return one-liner and it runs very slow.
Aren't they supposed to be the same?
Without one-liner
def memoize(func):
memo = dict()
def decorated(n):
if n not in memo:
memo[n] = func(n)
return memo[n]
return decorated
@memoize
def fib(n):
if n<=1:
return 1
else:
return fib(n-1) + fib(n-2)
print([ fib(i) for i in range(100,110)]) # runs very fast
With one-liner return
def memoize(func):
memo = dict()
def decorated(n):
return func(n) if n not in memo else memo[n]
return decorated
@memoize
def fib(n):
if n<=1:
return 1
else:
return fib(n-1) + fib(n-2)
print([ fib(i) for i in range(100,110)]) # very slow
Question
Aren't they supposed to be the same?
Why the return one-liner is much much slower than another one?
Can we write one-liner with different wordings so that it is equally fast?