[Tutor] Re: Tutor digest, Vol 1 #962 - 15 msgs

Christopher Smith csmith@blakeschool.org
Wed, 18 Jul 2001 02:15:04 -0500


>From: Mike Serpa <onav@yahoo.com>
>> a=[1,2,3,4]
>> b=[5,6,7]
>> c=[8,9,10,11,12]
>> 
>> n=len( reduce( lambda a,b:max(a,b), [a,b,c] ))
>> 
>> n is 5
>
>Couldn't we shorten this to:
>n=len(max(lists))   

Yep! Nice job.  Strunk and White would be proud.
That works, too:

>>> a=range(3)
>>> b=range(4)
>>> c=range(2)
>>> len( reduce( lambda a,b:max(a,b), [a,b,c] ))
4
>>> len(max(a,b,c))
4
>>> reduce(max, map(len, (a, b, c)))
4
>>> apply(max, map(len, (a, b, c)))
4
>>> max(map(len, (a, b, c)))
4

Danny's pathological case could be handled by your
approach by simply adding something else for the max to chew:

len(max([1],[]))

Which is a bit simpler than

max(map(len,([1],)))

(BTW, no particular reason for the reduce or apply, Mike...that's just
how the problem posed itself to me:  I have lists that I needed
to repeatedly apply max to.  I forgot that max already
repeats itself.)

So in a function you could have:

def pcolumns(...,*lists):
	n=len(max(lists,[]))


>
>It seems that everything I figure out how to do is already in a module
>somewhere.  Question for expert Python coders (or any lang.) Do you
>ever  get to the stage where you don't have to constantly look things
>up in the lang docs?

It's like learning new words.  If you never read books or talk
to people with bigger vocabularies than yours you always have
to use lots of little words to get your ideas across.  As I 
read the documentation and Python FAQ (non-operative but lots of
useful stuff).  I get more ideas about solving problems in
alternate ways and with less re-inventing.  Those that came
up with the modules had to have covered some of the same ground 
that you are covering.
>
>
>> 
>> 2) Instead of padding, you might consider using the try/except 
>> construction to not print the list elements that don't 
>> exist. 
>
>So I don't have to lace them then.

Right!
>
>So we get:
>
<cut the same thing that I had :-)>
>
>Great!
>We've gone from 20 lines to 15 to 9.  More importantly it's now much
>simpler.

And you've learned a few tricks on the way.
>
>
>The only thing I can think to add is a max number of columns so it
>doesn't go off the screen. Or if columns is > 4 then split into two
>tables. Or adjust columns to largest element, etc. Don't need to yet
>for what I'm using if for, but will be easier now. Thanks.

Exactly what I was thinking.  Here's something else
to think about.  BBEdit has a 'tabulate' tool which
will figure out teh optimal column spacings for you
based on the widths of everything in the columns.  You could
add the column headers to your lists to print and then run
through each list and find the longest element.  Then print
the titles on one line (if possible) and then the underscores
('_'*maxincolumni) and finally the data.

/c