```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ``` ```def nblocks(seq, block_len): ''' Divide the sequence "seq" to blocks of "block_len" size. Makes the last block big enough to hold the remainder. nblocks(range(10), 3) -> [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]] ''' # skip the last 2 blocks if len(seq) doesn't div perfectly. # if len(seq) does div perfectly - skip only 1 for i in range(0, len(seq) - 2 * block_len + 1, block_len): yield seq[i:i + block_len] # yield the last 1-2 blocks connected if len(seq) > block_len: yield seq[i + block_len:] print list(nblocks(range(9), 3)) print list(nblocks(range(10), 3)) print list(nblocks(range(11), 3)) print list(nblocks(range(12), 3)) print list(nblocks(range(13), 3)) print '---' print list(nblocks(range(10), 2)) print list(nblocks(range(10), 4)) ```
 ```1 2 3 4 5 6 7 8 ``` ```[[0, 1, 2], [3, 4, 5], [6, 7, 8]] [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]] [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9, 10]] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11, 12]] --- [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] [[0, 1, 2, 3], [4, 5, 6, 7, 8, 9]] ```