Generators, generator expressions, and loops
Peter
pacqa100 at yahoo.com.au
Fri Nov 16 21:02:01 EST 2018
Lovely, succinct answers.
On 17/11/2018 2:44 AM, Ian Kelly wrote:
> On Fri, Nov 16, 2018 at 7:57 AM Steve Keller <keller at no.invalid> wrote:
>> I have looked at generators, generator expressions, and iterators and
>> I try to get more familiar with these.
>>
>> 1. How would I loop over all (with no upper bound) integers or all
>> powers of two, for example?
>>
>> In C it would be
>>
>> for (int i = 0; ; i++) { ... } or for (int i = 1; ; i *= 2) { ... }
>>
>> In Python, I could define a generator
>>
>> def powers():
>> i = 1
>> while True:
>> yield(i)
>> i *= 2
>>
>> for i in powers():
>> ...
>>
>> More elegant are generator expressions but I cannot think of a way
>> without giving an upper limit:
>>
>> for i in (2 ** i for i in range(1000000)):
>> ...
>>
>> which looks ugly. Also, the double for-loop (and also the two loops
>> in the above exmaple, for + while in the generator) look unnatural,
>> somehow, i.e. loop over all elements which are created by a loop.
>>
>> Is there a more beautyful way?
> Some options:
>
> from itertools import count
>
> def powers():
> for i in count():
> yield 2 ** i
>
>
> for i in (2 ** i for i in count()):
> ...
>
>
> for i in map(lambda x: 2 ** x, count()):
> ...
>
>
> from functools import partial
> from operator import pow
>
> for i in map(partial(pow, 2), count()):
> ...
>
>
> Take your pick.
>
More information about the Python-list
mailing list