[Tutor] Counting matching elements in sequences

Pieter Lust pieter.lust at katho.be
Tue Dec 9 05:55:18 EST 2003


Hello,


Recently I wrote a function to count the matching elements in two tuples. It
looked like this:

def matches(s1, s2):
    """matches: count the number of matching elements in 2 sequences of
identical length (c-style)"""
    matches = 0
    for i in range(0, len(s1)):
        if s1[i] == s2[i]:
            matches += 1
    return matches

Then today I saw a post from Karl Pflaesterer, which inspired another
solution:

def matches2(s1, s2):
    """matches2: count the number of matching elements in 2 sequences of
identical length (lambda)"""
    return len(filter(lambda t: t[0] == t[1], zip(s1, s2)))

And then I tried to extend it for an arbitrary number of input sequences:

def matches3(*seqlist):
    """matches3: count the number of matching elements in sequences of
identical length (lambda)"""
    return len(filter(lambda t: list(t).count(t[0]) == len(t),
zip(*seqlist)))

To my novice eye,  matches3 does look quite complex. How would a seasoned
Python programmer write it? Am I missing a more obvious solution?


Thanks for any comment,

Pieter Lust





More information about the Tutor mailing list