[Tutor] Geometric sequence

Alan Gauld alan.gauld at btinternet.com
Thu Oct 31 01:01:00 CET 2013


On 30/10/13 17:08, 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.

You can add an if clause to the comprehension:

series = [2**x for x in range(7) if 2**x <= 60]

But that does mean you calculate the element twice and keep looping 
beyond the 'break' point.

Is there a better way of doing it that the following:
>
> for x in range(20):
>      series_element = 2**x
>      print series_element
>      if series_element > 60:
>          break

If you were stopping in the middle of a long series or if the 
calculation were more complex then the for loop might be faster
than the comprehension. But such things are best measured
once you have established that there is actually a problem
to solve.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list