Re: how to write a C-style for loop?



On Wed, 15 Feb 2006 10:20:13 +0000, ZeD wrote:

Ciao, John Salerno! Che stavi dicendo?

for (int i = 0; i < 50; i += 5)

How would that go in Python, in the simplest and most efficient way?

i=0
while i<50:
#...
i+=5

That's exceedingly unPythonic. In fact I'd go far to say it is bad
practice in just about any programming language that has for loops. Why on
earth would any sensible programmer want to manage the loop variable by
hand if the language can do it for you?


about range()/xrange(): what if you want to traslate this c-loop? for
(int i=1; i<50; i*=2)

That's a completely different question, so of course it has a completely
different answer. Here is one way:

for i in [2**n for n in range(6)]:
do_something(i)

Here is another:

for i in range(int(math.log(50)/math.log(2)+1)):
do_something(2**i)

Here is a third way:

i = 1
while i < 50:
do_something(i)
i *= 2

Here is a fourth way:

import operator
def looper(start, (op, finish), (op2, x)):
n = start
while op(n, finish):
yield n
n = op2(n, x)

loop = looper(1, (operator.__lt__, 50), (operator.__mul__, 2))

for i in loop:
do_something(i)



--
Steven.

.



Relevant Pages

  • Can you introduce some book about python?
    ... appending key-value pairs to a dict (Peter ... Is Python suitable for a huge, ... >> to the list on each loop... ...
    (comp.lang.python)
  • Re: Am I the only one who would love these extentions? - Python 3.0 proposals (long)
    ... Why is it nice enough to make it be a syntax addition, ... to point an image viewer/editor at a chunk of Python code. ... You argue consistancy to other keywords. ... Why is this new loop construct of yours useful enough ...
    (comp.lang.python)
  • Re: "also" to balance "else" ?
    ... some Python variant by using a different name, ... > after the loop makes it clear it evaluates after the loop is done. ... print "this is not a pipe" ... way to do it" there is already a strong bias against language ...
    (comp.lang.python)
  • Re: About alternatives to Matlab
    ... But whether a single loop is faster than several BLAS calls does not ... Bad Fortran 95 can easily be 25% lower than well-tuned C99. ... NumPy can be slower than equivalent C by an order of magnitude. ... manipulated within Python, not the speed of python code using NumPy ...
    (comp.lang.python)
  • Re: Can you introduce some book about python?
    ... You m,igth try my page of Python Book reviews at ... >> with dicts? ... >>> its sha hash into a dict on each loop. ... >>> My problem is that it doesn't rotate smoothly. ...
    (comp.lang.python)