searching in list

Chris Angelico rosuav at gmail.com
Mon May 30 09:41:00 EDT 2011


On Mon, May 30, 2011 at 10:58 PM, vino19 <vinograd19 at gmail.com> wrote:
> I want to make a function that is called only once per one argument. I mean I want to store data of function calling to prevent calling it again if there is no need.
> How to make it? For example I can make a global list that just consist of tuples
> [(arg1, res1), (arg2, res2), ...]. Ok, how to search if an arg135 in that list?
>
> Thanks for answering

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.)

Chris Angelico



More information about the Python-list mailing list