Lambda question

Terry Reedy tjreedy at udel.edu
Mon Jun 6 22:08:47 EDT 2011


On 6/6/2011 12:52 PM, Terry Reedy wrote:

> def group(seq, n):
> 'Yield from seq successive disjoint slices of length n & the remainder'
> if n<=0: raise ValueError('group size must be positive')
> for i in range(0,len(seq), n):
> yield seq[i:i+n]
>
> for inn,out in (
> (('',1), []), # no input, no output
> #(('abc',0), ValueError), # group size positive
> (('abc',1), ['a','b','c']),
> (('abcd',2), ['ab','cd']),
> (('abcde',2), ['ab', 'cd', 'e']), # could change this
> ):
> assert list(group(*inn)) == out, (inn,out)

I forgot to mention that any function that takes a 'sequence' as input 
should be tested with both strings and non-strings. I learned this when 
a function tested with one failed mysteriously with the other. Strings 
are unique in that indexing returns a slice (and hence a string) rather 
than a separate class of item. It this case, there is no indexing and no 
use of class to create new items. However, adding a couple of lines like
         (((),1), []),
         (((1,2,3,4),2), [(1,2), (3,4)]),
to the test sequence checks the current code and guards against future 
changes.

-- 
Terry Jan Reedy




More information about the Python-list mailing list