Santiago Caracol wrote:

> Hello,
> 
> I want to write a web application that does this:
> 
> (1) The user submits a query:
> 
> ---------------------------------
> | What is the answer? |
> ---------------------------------
> <Submit>
> 
> (2) The web server gives the user N answers and a button saying "More
> answers":
> 
> . answer 1
> . answer 2
> . answer 3
> 
> <More answers>
> 
> I am aware of several ways to do this: I could calculate all
> answers, but show only the first N of them. For certain kinds of
> calulations,
> I could use a kind of setoff argument. But I would like to do it in a
> more general
> and (hopefully) efficient way:
> 
> I want the function or object that calculates the answers to be
> "frozen" at the point at which it has already calculated N answers. If
> the function gets a <More answers>-signal within a reasonable period
> of time, it goes on producing more answers exactly at the point at
> which it got frozen. If no signal is sent, the function call is
> terminated automatically after
> M seconds.
> 
> Note that, although the program to be written is a web application,
> this is not a question about web application specific things. My only
> difficulty is how to "freeze" function calls.
> 
> Has anyone done something of this kind?

Python offers an elegant mechanism to calculate values on demand: the 
generator function:

>>> def calculate_answers():
...     for i in range(100):
...             print "calculating answer #%d" % i
...             yield i * i
...
>>> from itertools import islice
>>> gen = calculate_answers()

This builds the generator but doesn't run the code inside. Now let's look at 
the first three "answers":

>>> for answer in islice(gen, 3):
...     print "the answer is", answer
...
calculating answer #0
the answer is 0
calculating answer #1
the answer is 1
calculating answer #2
the answer is 4

If you repeat the last step you get the next three answers:

>>> for answer in islice(gen, 3):
...     print "the answer is", answer
...
calculating answer #3
the answer is 9
calculating answer #4
the answer is 16
calculating answer #5
the answer is 25

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to