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?
asked Dec 30, 2015 at 23:00
1-approximation
3211 gold badge4 silver badges13 bronze badges
2 Answers 2
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
answered Dec 30, 2015 at 23:07
Frerich Raabe
95.2k20 gold badges127 silver badges216 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
1-approximation
In fact, I have 'N' loops, one for each range(n*K,(n+1)*K).
user2357112
@1-approximation: Then you're going to have to clarify what
# do something is, and how the various # do somethings differ from each other.for loop_id in xrange(N):
for i in xrange(K):
k = K * loop_id + i
do_smth(loop_id, i, k)
answered Dec 30, 2015 at 23:16
Eugene Primako
2,8379 gold badges28 silver badges35 bronze badges
2 Comments
1-approximation
Thanks. If I want to keep the loop in range(K*(N+1)), can I still do it?
Eugene Primako
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.
lang-py
n = k//K