[Tutor] Counting matching elements in sequences

Karl Pflästerer sigurd at 12move.de
Tue Dec 9 15:36:12 EST 2003


On  9 Dec 2003, Magnus Lycka <- magnus at thinkware.se wrote:

> 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! :)

Yep I noticed it later; here the equality of True and 1 and False and 0
bites.

>>>> 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

I came up with nearly the same one.

def alleq(seq):
    k = seq[0]
    for i in seq:
        if i != k:
            return 0
    return 1


Sadly reduce might break if you have zero as first element.

> 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).

Right.

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




More information about the Tutor mailing list