[Python-talk] Generator Question

Kent Johnson kent37 at tds.net
Wed Aug 12 12:35:59 EDT 2009


On Wed, Aug 12, 2009 at 11:41 AM, <bruce.labitt at autoliv.com> wrote:
> python-talk-bounces at dlslug.org wrote on 08/12/2009 10:41:18 AM:

>> Anyways, here are the questions:
>> 1. Can a generator output an array instead of a single value at every
>> call?
>> 2. It is my understanding that once a generator has 'finished' the
> output
>> is null?  Is that true?
>> 3. Can a generator be reset or restarted?  How?
>>
>
> Happens every time...  OK, answers are:
> 1. Yes.
> 2. Nope, one gets a StopIteration exception.
> 3. Beazley gives an example.  For my case, I don't think I need to reset.
> I just need to call the generator again...

Right.

>> The power condition is calculated by computing FFTs of the generator
>> output.  The generator will be required to make say 100 arrays.  Once
> all
>> 100 arrays have been FFT'd, and the power computed, the optimizer will
>> make a decision as to how to change the sequence to get the desired
> power
>> output.  The generator will be reset and asked to use a new sequence as
>> its input.   Wash, lather, repeat until done...  I can tell that this is
>
>> going to be fun to debug...
>>
>> OK, I'm asking for it now...  Is this an OK approach?  Or am I out in
> the
>> weeds again?  I am bracing myself now...

It sounds fine :-) Beazley's chained generators might work very well for you
- initial generator creates the arrays
- next generator computes FFT
- next compute power

Output goes to the optimizer to make a decision, then start over.

One advantage to breaking it up this way is you can test each step
independently. You need a function to generate an array, a function to
compute FFT, and a function to compute power. Each of these can be
separately developed and tested. Then you have

seeds = [ <some sequence that defines the arrays to be created> ]
score = 0
while score < threshold:
  arrays = (make_array(seed) for seed in seeds)
  fft_results = (compute_fft(array) for array in arrays)
  powers = (compute_power(result) for result in fft_results)
  score, seeds = optimize(powers)

Kent


More information about the Python-talk mailing list