user4327204
user4327204

Reputation:

Converting C style for loop to python

How do you convert a c-style for loop into python?

for (int i = m; i >= lowest; i--)

The best that I came up with was:

i = mid
for i in range(i, low,-1):

Upvotes: 2

Views: 2712

Answers (4)

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

Where possible, the Python idiom is to loop over the items directly, not to count through them. Therefore an idiomatic way to count down would be for item in reversed(list): print item or to take a reversed slice >>> someList[m:lowest-1:-1]

If you are looping over items and also need a counter, Python has enumerate() to generate counting index numbers while looping. for index, value in enumerate(someList):

It's not always possible to do this, sometimes you are counting and not going over any other data except the numbers, and range() is fine - as the other answers suggest. But when you have a for (int i=... loop, see if you can change it to act directly on the data. Writing "C in Python" is no fun for anyone.

Upvotes: 1

jamylak
jamylak

Reputation: 133634

for i in range(m, low - 1, -1):

Keep in mind range is exclusive of the stop parameter.

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

The difference between this code and the C code is that in Python 2, a list is being constructed in memory by range so for very huge ranges this could be a problem. Replacing range with xrange would not build a list in memory and make the code practically the same. In Python 3 this issue no longer exists.

Upvotes: 7

Andy
Andy

Reputation: 50600

m = 20
low = 10

for i in range(m, low - 1, -1):
    print i

This will count down as expected:

20
19
18
17
16
15
14
13
12
11
10

range takes three parameters, a start, a stop and the increment between each step.

Upvotes: 1

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

m from where the loop start.

l where the loop stop, and range exclude last item so l-1 and

-1 for reverse array.

for i in range(m, l-1, -1):

Upvotes: 1

Related Questions