im plugging away at the problems at http://www.mathschallenge.net/index.php?section=project
im trying to use them as a motivator to get into advanced topics in
python.
one thing that Structure And Interpretation Of Computer Programs
teaches is that memoisation is good.
all of the memoize decorators at the python cookbook seem to make my
code slower.
is using a decorator a lazy and inefficient way of doing memoization?
can anyone point me to where would explain how to do it quickly. or is
my function at fault?
the code in question is as follows
"""
from memoize import memoize,memoize2
@memoize
def col(n, count):
if n == 1:
return count
elif n % 2 == 0:
return col(n/2, count+1)
else:
return col((3*n+1)/2, count+2)
import psyco
psyco.full()
start = time()
maxlength = 0
best = 0
for i in range(1, 1000001):
length = col(i,1)
if length maxlength:
maxlength = length
best = i
print maxlength, best
end = time()
print 'took', end-start 11 2498
sorry
memoize is http://aspn.activestate.com/ASPN/Coo.../Recipe/496879
memoize2 is http://aspn.activestate.com/ASPN/Coo.../Recipe/466320
im plugging away at the problems at http://www.mathschallenge.net/index.php?section=project
im trying to use them as a motivator to get into advanced topics in
python.
one thing that Structure And Interpretation Of Computer Programs
teaches is that memoisation is good.
all of the memoize decorators at the python cookbook seem to make my
code slower.
is using a decorator a lazy and inefficient way of doing memoization?
can anyone point me to where would explain how to do it quickly. or is
my function at fault?
the code in question is as follows
"""
from memoize import memoize,memoize2
@memoize
def col(n, count):
if n == 1:
return count
elif n % 2 == 0:
return col(n/2, count+1)
else:
return col((3*n+1)/2, count+2)
import psyco
psyco.full()
start = time()
maxlength = 0
best = 0
for i in range(1, 1000001):
length = col(i,1)
if length maxlength:
maxlength = length
best = i
print maxlength, best
end = time()
print 'took', end-start
At Friday 18/8/2006 17:14, th*************@gmail.com wrote:
>sorry memoize is http://aspn.activestate.com/ASPN/Coo.../Recipe/496879
This implementation uses cPickle to generate a key from the supplied
function arguments, which is very slow and defeats the purpose of memoizing.
In your example -function with no keyword arguments- use the much
simpler implementation from
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205NOT
the original recipe but the comment by Chris Spencer titled "A
working example".
Gabriel Genellina
Softlab SRL
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! http://www.yahoo.com.ar/respuestas
Gabriel Genellina wrote:
This implementation uses cPickle to generate a key from the supplied
function arguments, which is very slow and defeats the purpose of
memoizing.
depends on the cost of recreating an object, of course. it's a bit
surprising that so many programmers seem to think that there are "one
size fits all" solutions to caching and memoization...
</F> th*************@gmail.com wrote:
all of the memoize decorators at the python cookbook seem to make my
code slower.
if you want good performance, use the following pattern:
def col(n, count, memo={}):
try:
return memo[n, count]
except KeyError:
# ... calculate value ...
memo[n, count] = value
return value
for some access patterns, the following may be faster:
def col(n, count, memo={}):
value = memo.get((n, count))
if value is None:
# ... calculate value ...
memo[n, count] = value
return value
to get maximum performance, make the memo dictionary public, and make
the check at the original call site.
is using a decorator a lazy and inefficient way of doing memoization?
lazy, yes. inefficient? it depends.
</F> th*************@gmail.com wrote:
im plugging away at the problems at http://www.mathschallenge.net/index.php?section=project
im trying to use them as a motivator to get into advanced topics in
python.
one thing that Structure And Interpretation Of Computer Programs
teaches is that memoisation is good.
all of the memoize decorators at the python cookbook seem to make my
code slower.
is using a decorator a lazy and inefficient way of doing memoization?
can anyone point me to where would explain how to do it quickly. or is
my function at fault?
Your problem is that you are mixing psyco and memoize decorators;
psyco cannot accelerate inner functions that use nested scopes (see http://psyco.sourceforge.net/psycogu...supported.html ).
You could try using the memoize decorator from: http://wiki.python.org/moin/PythonDecoratorLibrary ,
which doesn't use functions with closures, or use Fredrik Lundh's
solution which puts memoization directly into the function.
Ziga
thanks, i was not just being lazy. i wanted to play with decorators and
tell people on the forums how cool python is :)
cheers for getting back to me, i could have done that myself i think,
bar the error checking. do you have any links on good practice in
python (i do think i am very lazy re: error checking and would like to
make myself better)
cheers, tom
Fredrik Lundh wrote: th*************@gmail.com wrote:
all of the memoize decorators at the python cookbook seem to make my
code slower.
if you want good performance, use the following pattern:
def col(n, count, memo={}):
try:
return memo[n, count]
except KeyError:
# ... calculate value ...
memo[n, count] = value
return value
for some access patterns, the following may be faster:
def col(n, count, memo={}):
value = memo.get((n, count))
if value is None:
# ... calculate value ...
memo[n, count] = value
return value
to get maximum performance, make the memo dictionary public, and make
the check at the original call site.
is using a decorator a lazy and inefficient way of doing memoization?
lazy, yes. inefficient? it depends.
</F>
does not seem to work for standalone functions, this is a method
decorator only then?
Traceback (most recent call last):
File "prob14memoize.py", line 94, in ?
length = col(i,1)
File "prob14memoize.py", line 49, in __call__
object = self.cache[args] = self.fn(self.instance, *args)
AttributeError: 'Memoize' object has no attribute 'instance'
cheers, tom
Gabriel Genellina wrote:
At Friday 18/8/2006 17:14, th*************@gmail.com wrote:
sorry
memoize is http://aspn.activestate.com/ASPN/Coo.../Recipe/496879
This implementation uses cPickle to generate a key from the supplied
function arguments, which is very slow and defeats the purpose of memoizing.
In your example -function with no keyword arguments- use the much
simpler implementation from
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205NOT
the original recipe but the comment by Chris Spencer titled "A
working example".
Gabriel Genellina
Softlab SRL
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! http://www.yahoo.com.ar/respuestas
am i correct in thinking that psyco will just not accelerate, rather
than break code it cannot deal with? that has been a pretty standard
import on all my programs
tom
Ziga Seilnacht wrote: th*************@gmail.com wrote:
im plugging away at the problems at http://www.mathschallenge.net/index.php?section=project
im trying to use them as a motivator to get into advanced topics in
python.
one thing that Structure And Interpretation Of Computer Programs
teaches is that memoisation is good.
all of the memoize decorators at the python cookbook seem to make my
code slower.
is using a decorator a lazy and inefficient way of doing memoization?
can anyone point me to where would explain how to do it quickly. or is
my function at fault?
Your problem is that you are mixing psyco and memoize decorators;
psyco cannot accelerate inner functions that use nested scopes (see http://psyco.sourceforge.net/psycogu...supported.html ).
You could try using the memoize decorator from: http://wiki.python.org/moin/PythonDecoratorLibrary ,
which doesn't use functions with closures, or use Fredrik Lundh's
solution which puts memoization directly into the function.
Ziga
I suppose that lesson should not suprise me, programming is a subtle
art that i need spend some time mastering
thanks to all that have replied
tom
Fredrik Lundh wrote:
Gabriel Genellina wrote:
This implementation uses cPickle to generate a key from the supplied
function arguments, which is very slow and defeats the purpose of
memoizing.
depends on the cost of recreating an object, of course. it's a bit
surprising that so many programmers seem to think that there are "one
size fits all" solutions to caching and memoization...
</F>
At Saturday 19/8/2006 07:58, th*************@gmail.com wrote:
>am i correct in thinking that psyco will just not accelerate, rather than break code it cannot deal with? that has been a pretty standard import on all my programs
Don't optimize what doesn't deserve optimization... That's a pretty
standard mantra.
Gabriel Genellina
Softlab SRL
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! http://www.yahoo.com.ar/respuestas
At Saturday 19/8/2006 07:56, th*************@gmail.com wrote:
>does not seem to work for standalone functions, this is a method decorator only then?
Traceback (most recent call last):
File "prob14memoize.py", line 94, in ?
length = col(i,1)
File "prob14memoize.py", line 49, in __call__
object = self.cache[args] = self.fn(self.instance, *args) AttributeError: 'Memoize' object has no attribute 'instance'
For a standalone function, you should remove __del__ and
self.instance, but I haven't tried it...
Gabriel Genellina
Softlab SRL
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! http://www.yahoo.com.ar/respuestas This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Chris Reedy |
last post by:
I would like to memoize (I think I've got that right) a collection of
functions for a project I'm working.
<Aside for those not familiar with memoizing functions:>
Given:
def foo(a,b,c):
return <result of large ugly computation>
|
by: Michael Hohn |
last post by:
Hi,
under python 2.2, the pickle/unpickle sequence incorrectly restores
a larger data structure I have.
Under Python 2.3, these structures now give an explicit exception from
Pickle.memoize():
assert id(obj) not in self.memo
I'm shrinking the offending data structure down to find the problem
|
by: km |
last post by:
Hi all,
was going thru the new features introduced into python2.4 version.
i was stuck with 'decorators' - can someone explain me the need of such a thing called decorators ?
tia
KM
|
by: Ron_Adam |
last post by:
I was having some difficulty figuring out just what was going on with
decorators. So after a considerable amount of experimenting I was
able to take one apart in a way. It required me to take a closer look
at function def's and call's, which is something I tend to take for
granted.
I'm not sure this is 100%, or if there are other ways to...
|
by: Ron_Adam |
last post by:
Hi, Thanks again for all the helping me understand the details of
decorators.
I put together a class to create decorators that could make them a lot
easier to use.
It still has a few glitches in it that needs to be addressed.
(1) The test for the 'function' object needs to not test for a string
but an object type instead.
| |
by: Doug |
last post by:
I am looking at using the decorator pattern to create a rudimentary
stored proc generator but am unsure about something. For each class
that identifies a part of the stored proc, what if I want to add a
value dynamically. I'm including some code to show what I mean. This
is real basic on what I want to do:
using System;
namespace...
|
by: thebjorn |
last post by:
I seem to be writing the following boilerplate/pattern quite
frequently to avoid hitting the database until absolutely necessary,
and to only do it at most once:
class Foo(object):
@property
def expensive(self):
if not hasattr(self, '_expensiv'):
self._expensive = <insert expensive db call here>
return self._expensive
|
by: ankitks.mital |
last post by:
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
|
by: thomas.karolski |
last post by:
Hi,
I would like to create a Decorator metaclass, which automatically
turns a class which inherits from the "Decorator" type into a
decorator.
A decorator in this case, is simply a class which has all of its
decorator implementation inside a decorator() method. Every other
attribute access is being proxied to decorator().getParent().
...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |