Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop with custom steps in python

I can make simple for loops in python like:

for i in range(10):

However, I couldn't figure out how to make more complex ones, which are really easy in c++.

How would you implement a for loop like this in python:

for(w = n; w > 1; w = w / 2)

The closest one I made so far is:

for w in reversed(range(len(list)))
like image 948
gen Avatar asked Jul 30 '13 10:07

gen


People also ask

How do you specify a step in a for loop in Python?

To iterate through an iterable in steps, using for loop, you can use range() function. range() function allows to increment the “loop index” in required amount of steps.

How do you specify an increment in a for loop in Python?

5. Python For Loop With Incremental Numbers. Apart from specifying a start-value and end-value, we can also specify an increment-value. For example, if you want a sequence like this: 1, 3, 5, 7, 9, …, then the increment-value in this case would be 2, as we are incrementing the next number by 2.

How do you define step in Python?

Python range step A step is an optional argument of a range(). It is an integer number that determines the increment between each number in the sequence. i.e., It specifies the incrementation. The default value of the step is 1 if not specified explicitly.

How do you repeat a step in Python?

The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.


6 Answers

for i in range(0, 10, 2):
    print(i)

>>> 0
>>> 2
>>> 4
>>> 6
>>> 8

http://docs.python.org/2/library/functions.html

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
like image 111
the5fire Avatar answered Oct 16 '22 05:10

the5fire


First and foremost: Python for loops are not really the same thing as a C for loop. They are For Each loops instead. You iterate over the elements of an iterable. range() generates an iterable sequence of integers, letting you emulate the most common C for loop use case.

However, most of the time you do not want to use range(). You would loop over the list itself:

for elem in reversed(some_list):
    # elem is a list value

If you have to have a index, you usually use enumerate() to add it to the loop:

for i, elem in reversed(enumerate(some_list)):
    # elem is a list value, i is it's index in the list

For really 'funky' loops, use while or create your own generator function:

def halved_loop(n):
    while n > 1:
        yield n
        n //= 2

for i in halved_loop(10):
    print i

to print 10, 5, 2. You can extend that to sequences too:

def halved_loop(sequence):
    n = -1
    while True:
        try:
            yield sequence[n]
        except IndexError:
            return
        n *= 2

for elem in halved_loop(['foo', 'bar', 'baz', 'quu', 'spam', 'ham', 'monty', 'python']):
    print elem

which prints:

python
monty
spam
foo
like image 33
Martijn Pieters Avatar answered Oct 16 '22 04:10

Martijn Pieters


For your exact example, you probably wouldn't use a for loop at all, but a while loop:

w = n
while w > 1:
    do stuff
    w = w / 2
like image 30
Daniel Roseman Avatar answered Oct 16 '22 04:10

Daniel Roseman


Something like for i in [n/(2**j) for j in range(int(math.log(n))+1)]

like image 41
Atmaram Shetye Avatar answered Oct 16 '22 06:10

Atmaram Shetye


You need to use a generator. You could implement this as follows:

def stepDown(n):
    while n>1:
        yield n
        n = n/2

for i in stepDown(n):
    print i # or do whatever else you wish.

Note that this generalizes easily to other complicated patterns you may have in mind.

like image 32
16 revs, 2 users 100% Avatar answered Oct 16 '22 04:10

16 revs, 2 users 100%


For the more general case, you could create a custom generator function, that takes a start, stop, and a function for generating the next step from the last:

def my_range(start, stop, f):
    x = start
    while x < stop if stop > start else x > stop:
        yield x
        x = f(x)

>>> list(my_range(1, 1024, lambda x: x*2))
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

>>> list(my_range(1000, 1, lambda x: x/2))
[1000, 500.0, 250.0, 125.0, 62.5, 31.25, 15.625, 7.8125, 3.90625, 1.953125]
like image 38
tobias_k Avatar answered Oct 16 '22 06:10

tobias_k