[Tutor] Geometric sequence

Dave Angel davea at davea.name
Thu Oct 31 03:18:18 CET 2013


On 30/10/2013 13: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. 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
> print series
>

Change from range to xrange, if you want this to be generally more
efficient.  Doesn't matter for small numbers like this, but I assume
you're asking about a potentially much larger value and/or a much larger
multiplier.

If you're going to print them, and not build a list, then the while loop
is certainly "better" than the comprehension.

On the other hand, if you need the list (as you do in your first
example), then the comprehension with a conditional is probably clearer.
 And then if performance becomes an issue, you can figure an upper bound
(which in this case is trivial using logs), and just make sure the
xrange is just large enough to exceed the value you want.

Finally, if you really want efficiency, then apply some algebra to the
problem, and don't loop at all.

-- 
DaveA




More information about the Tutor mailing list