Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write this algorithm in a python code?

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?

like image 297
1-approximation Avatar asked Dec 30 '15 23:12

1-approximation


2 Answers

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
like image 66
Frerich Raabe Avatar answered Sep 24 '22 02:09

Frerich Raabe


for loop_id in xrange(N):
    for i in xrange(K):
       k = K * loop_id + i
       do_smth(loop_id, i, k)
like image 31
Eugene Primako Avatar answered Sep 23 '22 02:09

Eugene Primako