[Tutor] Counting matching elements in sequences

Karl Pflästerer sigurd at 12move.de
Tue Dec 9 16:31:40 EST 2003


On  9 Dec 2003, Gregor Lingl <- glingl at aon.at wrote:


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


> Actually, if you wanted to avoid copying seq and at
> the same time make the function work for empty
> sequences you had to write something like:

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

or simply:

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

if we define empty sequences to be equal.


> or, how would you avoid
> "using len on the original sequence"?

see the above.


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




More information about the Tutor mailing list