Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6666

Re: searching in list

References <cec1aa77-86b3-4bff-8286-a84c823750d2@glegroupsg2000goo.googlegroups.com> <BANLkTikQ8cR72PPqxrv5ajFrQnDBg5NN5A@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2011-05-30 10:32 -0600
Subject Re: searching in list
Newsgroups comp.lang.python
Message-ID <mailman.2274.1306773179.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, May 30, 2011 at 7:41 AM, Chris Angelico <rosuav@gmail.com> wrote:
> If you're always going to look them up by the argument, the best way
> would be to use a dictionary:
> cache={arg1: res1, arg2: res2, ...}
>
> Then you can search with a simple: cache[arg135]
>
> You can add things with: cache[arg135]=res135
>
> This works best if the argument is an immutable and fairly simple
> type. For instance, you could calculate Fibonacci numbers in a naive
> and straightforward way:
>
> def fib(n,cache={}):
>  if n in cache: return cache[n]
>  ret=n if n<2 else fib(n-1)+fib(n-2) # This bit actually calculates fib(n)
>  cache[n]=ret
>  return ret
>
> Of course, this is a poor algorithm for calculating Fibonacci numbers,
> but it does demonstrate the cache. It's recursive, meaning that if it
> has fib(50) in its cache and it is asked for fib(60), it will find and
> make use of the cached element.
>
> (Note the sneaky way of storing a cache dictionary. A function's
> default arguments are evaluated once, so this will use the same
> dictionary for every call.)

If you're using Python 3.2, the functools.lru_cache decorator will do
the caching for you, and without modifying the function arguments.  By
default it stores only the 100 most recent results, but you can make
the storage unbounded by passing in the argument maxsize=None.  Then
the Fibonacci example becomes:

@functools.lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-2) + fib(n-1)

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

searching in list vino19 <vinograd19@gmail.com> - 2011-05-30 05:58 -0700
  Re: searching in list Dave Angel <davea@ieee.org> - 2011-05-30 09:27 -0400
  Re: searching in list Chris Angelico <rosuav@gmail.com> - 2011-05-30 23:41 +1000
  Re: searching in list Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-30 10:32 -0600

csiph-web