[Tutor] print as columns [using apply()]
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 17 Jul 2001 14:35:58 -0700 (PDT)
On Tue, 17 Jul 2001, Danny Yoo wrote:
> > You probably want to use: reduce(max, map(len, seq_o_lists))
> >
> > >>> reduce(max, map(len, (a, b, c)))
>
>
> This problem shows one instance where apply() might be useful: max() can
> take in as many arguments as we can feed into it:
>
> ###
> >>> max(3, 1, 4, 1, 5, 9, 2, 6)
> 9
> ###
>
> so we don't really even need the reduce if we use the apply() function:
>
> ###
> apply(max, map(len, (a, b, c)))
> ###
Whoops! I take it back --- there is one particularly evil case where
apply() doesn't apply:
###
>>> apply(max, map(len, ([1],))) ## oh no!
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: min() or max() arg must be a sequence
###
The guilt is not really on apply(), but max() --- max() can't handle a
single argument: it always assumes that it works with at least two:
###
>>> max(42)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: min() or max() arg must be a sequence
###
On the other hand, reduce() should work on this pathological example:
###
>>> reduce(max, map(len, ([1],)))
1
###
I must remind myself to test my programs with small "boundary" cases, just
to make sure nothing leaks out... *grin*