Re: [Tutor] Counting matching elements in sequences

Magnus Lycka magnus at thinkware.se
Tue Dec 9 14:35:41 EST 2003


Karl Pflästerer wrote:
> That won't work (I first thought of the same solution) because x == y
> returns True or False not x or y (with two elemenstit works, with three
> it breaks).

True!
 
> So you need a function like alleq
> 
> def alleq(seq):
>     return seq[0] == reduce(lambda s, t: s==t and t, seq)

That doesn't work either! :)

>>> def alleq(seq): 
    return seq[0] == reduce(lambda s, t: s==t and t, seq) 

>>> alleq([0,2,0])
True

Perhaps it's best to skip the "clever" lambda and reduce
tricks completely! This works (I think):

def alleq(seq):
    for item in seq[1:]:
        if item != seq[0]:
            return False
    return True

It also works correctly with 0 or 1 elements in the
sequence (assuming that we consider an empty list to
have all elements equal--at least there are no 
differences).

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list