[Tutor] Counting matching elements in sequences
Karl Pflästerer
sigurd at 12move.de
Tue Dec 9 14:12:12 EST 2003
On 9 Dec 2003, Magnus Lycka <- magnus at thinkware.se wrote:
> import operator
> def matches4(*seqlist):
> allSame = 0
> for elements in zip(*seqlist):
> allSame += reduce(operator.eq, elements)
> return allSame
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).
> or if you prefer lambda to importing operator...
> def matches4(*seqlist):
> allSame = 0
> for elements in zip(*seqlist):
> allSame += reduce(lambda x,y: x==y, elements)
> return allSame
Try the simple
>>> reduce(operator.eq, [2,2,2])
False
So you need a function like alleq
def alleq(seq):
return seq[0] == reduce(lambda s, t: s==t and t, seq)
>>> alleq([2,2,2])
True
>>>
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list