[Tutor] fibonacci [caching] [What's the precedence of "not
foo in bar"?]
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri Feb 14 18:01:02 2003
On Fri, 14 Feb 2003, Gregor Lingl wrote:
> And what about this?
>
> def fib(n, cache={0:0, 1:1}):
> if not n in cache:
> cache[n] = fib(n-2) + fib(n-1)
> return cache[n]
Hi Gregor,
I feel a little uncomfortable with the 'not n in cache' part: the reason
is because it takes a little effort deciding if Python will interpret it
as:
(not n) in cache ## Version 1
or
not (n in cache) ## Version 2
There is a distinct difference between the meanings! Which way will it
go? Let's test it by deliberately writing a fork in the road.
text_expression = not "foo" in {0 : 'zero', "foo" : "bar"}
This expression is specifically tailored to show which fork Python takes.
What do you think this test expression evaluates to?
Anyway, because of the potential confusion, we'll often use:
x not in L
rather than
not x in L
because it's just not really productive to play these precedence games,
even though it can be fun. *grin*