[Tutor] Counting matching elements in sequences
Gregor Lingl
glingl at aon.at
Tue Dec 9 16:00:31 EST 2003
>>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, how would you avoid
"using len on the original sequence"?
Gregor
More information about the Tutor
mailing list