regarding memoize function
ankitks.mital at gmail.com
ankitks.mital at gmail.com
Fri Apr 4 01:24:14 EDT 2008
On Apr 3, 8:04 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
> En Thu, 03 Apr 2008 21:21:11 -0300, Dan Bishop <danb... at yahoo.com>
> escribió:
>
>
>
>
>
> > On Apr 3, 6:33 pm, ankitks.mi... at gmail.com wrote:
> >> I saw example of memoize function...here is snippet
>
> >> def memoize(fn, slot):
> >> def memoized_fn(obj, *args):
> >> if hasattr(obj, slot):
> >> return getattr(obj, slot)
> >> else:
> >> val = fn(obj, *args)
> >> setattr(obj, slot, val)
> >> return val
> >> return memoized_fn
>
> >> and I am really clueless, about what it does. I know in general we try
> >> to keep computed values for future usage. But I am having hard-time
> >> visualizing it.
> >> What is obj here? and what does *args means?
>
> > *args is Python's syntax for variadic functions.
>
> In case the strange name gives you nothing, see section 4.7 in the
> Tutorial [1]
> For a much simpler implementation, see this FAQ entry [2]
>
> [1]http://docs.python.org/tut/node6.html#SECTION006700000000000000000
> [2] http://www.python.org/doc/faq/general/#why-are-default-values-shared-...
>
> --
> Gabriel Genellina- Hide quoted text -
>
> - Show quoted text -
Thanks Gabriel and Dan,
But I am still confuse on...
what is obj?
Let say
def f(node): return max(node.path_cost+h(node), getattr(node, 'f', -
infinity))
f = memoize(f,'f')
what is this doing?
I am passing string 'f' as second argument? right? so evertime in
function memoize,
I am doing hasattr(obj, slot), I am saying hasattr(obj, 'f')?
I kindof understand that I am returning maximum of pre-computed
value(if there is already) vs. new calculation.
But syntax is throwing me off.
More information about the Python-list
mailing list