[Tutor] Re: Bunch lists into sublists via alternation

Christopher Smith csmith@blakeschool.org
Wed, 18 Jul 2001 16:50:16 -0500


> Re: Bunch lists into sublists via alternation
> But i can't figure out how to get the:
> 
> a = (1,9,1,9,1,9)
> b = (1,9,7,1,9,7,1,9,7)
> seqSplit(a,2) --> ([1, 1, 1], [9, 9, 9])"""
> seqSplit(b,3) --> ([1, 1, 1], [9, 9, 9], [7, 7, 7])"""
> 
> type arrangement, particularly since i want it to work for any
unpredetermined
> number of sub-lists. I've got a kludge that works only for the case of
seqSplit(x,2),
> but i can't get anything to work for seqSplit(x,n) where n is anything
else.

By writing down the sequence you want to get you might see the pattern:

seqSplit(a,2) you want

    0,2,4 then
    1,3,5

seqSplit(b,3) you want

    0,3,6 then
    1,4,7 then
    2,5,8

What you don't see with these two examples is that the number
of rows is always n and the number of columns will be however
many n-steps could be taken through the list. If the seqeunce 
is nn units long then these indices can be given by:

    m = nn/n + nn % n  # ceil(nn/n)
    for i in range(n):
        for j in range(i,i+m+n,n): # +m b/c you need that many past i 
                                   # and +n to give you the last one
            print j,
        print


When you try access elements from the list, however, if the
list isn't m*n units long you will generate an IndexError
which, as for the Column Printing program that we have been
discussing can be handled with the try: construction:

    try:
        print l[j],
    except IndexError:
        print None

/c