How make the judge with for loop?

Peter Otten __peter__ at web.de
Sun Oct 16 05:22:36 EDT 2016


380162267qq at 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:
    sb[j].append(chars[i])
    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)
try:
    while True:
        for sublist in sb[:n]:
            sublist.append(next(chars))
        for sublist in sb[n-2: 0: -1]:
            sublist.append(next(chars))
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):
    sublist.append(c)

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




More information about the Python-list mailing list