如何在python代码中编写此算法?

时间:2015-12-30 23:00:37

标签: python algorithm

我有以下代码。

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
    ...
    ...

'做某事'很难解释,但我用矫揉造作n = p。

取而代之

我如何明确地写这个?

更具体地说,如果对于p = 0到N,k在集合{p * K,...,(p + 1)* K-1}中,则执行某些操作。我怎么能在代码中做到这一点?

2 个答案:

答案 0 :(得分:5)

你可能只有三个循环,没有?

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

答案 1 :(得分:3)

for loop_id in xrange(N):
    for i in xrange(K):
       k = K * loop_id + i
       do_smth(loop_id, i, k)