[Tutor] Geometric sequence

Andreas Perstinger andipersti at gmail.com
Thu Oct 31 08:25:20 CET 2013


On 31.10.2013 04:00, bob gailer wrote:
> On 10/30/2013 1:08 PM, Peter O'Doherty wrote:
>> Hi List,
>>
>> I know a geometric sequence can be produced by:
>>
>> series = [2**x for x in range(7)]
>>
>> But I would like to curtail the sequence before the last element
>> excedes a certain value.
> import itertools
> series = [2**x for x in itertools.takewhile(lambda x: 2**x<60, range(7))]

If you first produce an infinite geometric series and take only the 
elements up to a certain limit you avoid calculating 2**x twice:

 >>> import itertools as it
 >>> [x for x in it.takewhile(lambda x: x < 60, (2**x for x in 
it.count(0)))]
 >>> [1, 2, 4, 8, 16, 32]

Bye, Andreas



More information about the Tutor mailing list