6

I have the following code.

for k in range( ( N + 1 ) * K ):
    if k >= 0 and k <= K-1:
        # do something
        # n = 0
    elif k >= K and k <= 2*K-1:
        # do something
        # n = 1
    elif k >= 2*K and k <= 3*K-1:
        # do something
        # n = 2
    ...
    ...

The 'do something' is complicated to explain but I replaced it with the affectation n = p.

How can I write this explicitly?

More specifically, if k is in the set {p*K,...,(p+1)*K-1} for p = 0 to N, then do something. How can I do it in a code?

1
  • Are you looking for a way to compute n from k? n = k//K Commented Dec 30, 2015 at 23:50

2 Answers 2

5

You could just have three loops, no?

for k in range(K):
  # do something
for k in range(K, 2*K-1):
  # do something
for k in range(2*K-1, (N+1)*K):
  # do the rest
Sign up to request clarification or add additional context in comments.

2 Comments

In fact, I have 'N' loops, one for each range(n*K,(n+1)*K).
@1-approximation: Then you're going to have to clarify what # do something is, and how the various # do somethings differ from each other.
3
for loop_id in xrange(N):
    for i in xrange(K):
       k = K * loop_id + i
       do_smth(loop_id, i, k)

2 Comments

Thanks. If I want to keep the loop in range(K*(N+1)), can I still do it?
If range [0, K*(N+1)] is ok for you, you can just change range limits (from my piece of code) to N+2 and K+1 accordingly. If you do not want to have number K*(N+1) in the range - probably some hack (i.e. handling this case separately) will be required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.