Re: [Tutor] Sequence Comparison
Magnus Lycka
magnus at thinkware.se
Wed Jan 14 16:25:23 EST 2004
Michael Janssen wrote:
> python compares each element from left to right until it founds a pair
> of element, where the condition (<) is true:
> 1 < 1 ---> python find's: not true therefore:
> 2 < 2 ---> not true, next try
> 3 < 4 ---> true. Overall condition is true
Wrong. Python only goes to the next element in a sequence
as long as all the previous element pairs compared equal.
If > is true for a pair, False is returned at once.
No element is less than any element, so it looks like
this...roughly.
(lhs = left hand side, you guess what rhs is)
def less_than(lhs, rhs):
# Is lhs a sequence? (i.e. it has a length)
if hasattr(lhs, '__len__'):
# Are they both sequences?
if hasattr(rhs, '__len__'):
# Yes they are!
# Either empty?
if len(rhs) == 0:
# lhs is either equal or greater
return False
elif len(lhs) == 0:
# Nothing is less than something
return True
else:
# Both are non-empty
# Compare first elements
if lhs[0] < rhs[0]:
return True
elif lhs[0] == rhs[0]:
return less_than(lhs[1:], rhs[1:])
else:
return False
else:
# Only lhs is a sequence. Make the arbitrary decision
# that a sequence is always greater than a non-sequence
return False
else:
# lhs is no sequence. Is rhs a sequence?
if hasattr(rhs, '__len__'):
# As we just said, sequence is greater...
return True
else:
# Neither is a sequence, assume that we understand < here.
return lhs < rhs
In real life, there are other non-obvious non-sequences, such as classes,
modules, files and mappings etc.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus at thinkware.se
More information about the Tutor
mailing list