[Tutor] using the reduce function

Karl Pflästerer sigurd at 12move.de
Thu Jan 22 19:37:18 EST 2004


On 23 Jan 2004, Christopher Spears <- cspears2002 at yahoo.com wrote:

> Yet another homework problem is giving me fits.  Here
> it goes:

> Use the reduce function to find the length of the
> longest string in a list of strings.

> I have been banging my head against the wall with this
> one.  Ouch!  I figured out how to do it another way
> using control structures:

>>>> strings = ['long', 'longer', 'longest']
>>>> for i in range(len(strings)):
> 	count = 0
> 	if len(strings[i]) > count:
> 		count = len(strings[i])

> 		
>>>> count
> 7

> So how do I use the logic of this script and apply it
> to the problem?

You don't use it.  Above is an imperative style solution but with reduce
you have to think functional.

First, think what reduce does; it takes a sequence, a function with two
values and calls that function several times on the items of the
sequence.  The sequence is processed from left to right.  The first call
takes item0 and item1 from the sequence applies the function to them and
calls the function again with the return value and item2 and calls the
function again with the return value and itemm3 and calls ...

Above ism't ever true since you can give an initial value to reduce as
third argument.  Then the first call will apply the function to initial
value and item0.  From then on it's the same.

The value of the last function call is the return value of reduce.

So what you need is a function which tells you if one string is longer
than another.

That should be simple:

def longer (seq1, seq2):
    if len(seq1) > len(seq2): return seq1
    else: return seq2


So and now you just have to combine it with reduce.

def longest (seq):
    return reduce(longer, seq)


That returns the string but you need the length.


def longest (seq):
    return len(reduce(longer, seq))


If you are in the real functional mood (that's a good one to have) you
can write it as one function; you just have to write the if clause a bit
different since Python lambdas are weak.

def longest (seq):
    return len(reduce(lambda seq1, seq2: len(seq1) > len(seq2) and seq1 or seq2,
                      seq))

lambda seq1, seq2: len(seq1) > len(seq2) and seq1 or seq2
is the longer function; read about booleans and short circuit evaluation
to understand how it works.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list