38016226...@gmail.com wrote:

> c="abcdefghijk"
> len=len(c)
> n is a int
> sb=[[] for i in range(n)]
>     while (i < len) {
>         for (int j = 0; j < n && i < len; j++)
>             sb[j].append(c[i++]);
>         for (int j = n-2; j >= 1 && i < len; j--) //
>             sb[j].append(c[i++]);
>     }
> How to translate to python? I tried but my python code is really stupid

It would still be good to provide it or a least a complete runnable C 
source. A description of the problem in plain English would be helpful, too.

What follows are mechanical translations of what I think your original C 
code does.

(1) You can use a while loop to replace C's for

# example: first for loop
j = ;
while j < n and i < length:
    i += 1
    j += 1

which should be straight-forward, or 

(2) you can run a for loop until an exception is raised:

chars = "abcdefghijk"
chars = iter(chars)
    while True:
        for sublist in sb[:n]:
        for sublist in sb[n-2: 0: -1]:
except StopIteration:
    pass # we ran out of characters

(3) If you concatenate the two list slices into one, and with a little help 
from the itertools (while True... becomes itertools.cycle()) you get:

up = sb[:n]
down = sb[n-2: 0: -1]

for sublist, c in zip(cycle(up + down), chars):

(All untested code, you should check especially the slice indices)


Reply via email to