[Tutor] Counting matching elements in sequences

Gregor Lingl glingl at aon.at
Tue Dec 9 15:13:06 EST 2003



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

What do you think about:

 >>> def alleq(seq):
...     return seq == seq[:1]*len(seq)
...
 >>> alleq("")
True
 >>> alleq((1,))
True
 >>> alleq([1,1])
True
 >>> alleq((1,2))
False
 >>>

Gregor




More information about the Tutor mailing list