|
Title: fancy rich comparisons and MAXIMUM ANY and MINIMUM objects...
Submitter: Alex Naanou
(other recipes)
Last Updated: 2004/10/28
Version no: 1.2
Category:
Algorithms
|
|
1 vote(s)
|
|
|
|
Description:
here we will see an example of template comparisons based on a logical ANY object.
also this recipe provides alternative implementations of the absolute maximum and minimum objects (for more details on them see PEP326 http://www.python.org/peps/pep-0326.html).
Source: Text Source
__version__ = '''0.0.01'''
__sub_version__ = '''20041028004506'''
__copyright__ = '''(c) Alex A. Naanou 2003'''
class _Compare(object):
'''
'''
def __init__(self, eq):
self._eq = eq
def __cmp__(self, other):
return self._eq
def __eq__(self, other):
return self._eq == 0
def __ne__(self, other):
return self._eq != 0
def __gt__(self, other):
return self._eq > 0
def __ge__(self, other):
return self._eq >= 0
def __lt__(self, other):
return self._eq < 0
def __le__(self, other):
return self._eq <= 0
ANY = _Compare(0)
MAXIMUM = _Compare(1)
MINIMUM = _Compare(-1)
if __name__ == '__main__':
print (ANY, (ANY, ANY)) == (1, (2, 3))
print (lambda o: \
type(o) is tuple \
and len(o) == 2 \
and type(o[1]) is tuple \
and len(o[1]) == 2
)( (1, (2, 3)) )
print ([ANY, 123], 'string', (ANY,), ANY) == ([2, 123], 'string', (0.1,), (1, 2,))
Discussion:
the code here is mostly self explanatory... :)
P.S. here is a fun little piece of code that demonstrates the asymmetry of pythons comparison operations:
print ANY == MAXIMUM # this is True
print MAXIMUM > ANY # this is also True
print MAXIMUM == ANY # and this is False!
e.g. we can say that the term "anything" includes an absolute maximum, but the absolute maximum is larger than anything! :))
|
|
Add comment
|
|
Number of comments: 2
a simple (?) question, Alain Pointdexter, 2005/12/06
Great recipe!
I have a question though. How can i do the following:
assert (ANY,'x')==('a','b','c',....,'x')
My problem is that i have a list of tuples and i want to find the one that ends with 'x'
mylistoftuples=[('w',),('r','t'),....,('a','b','c')]
idx=mylistoftuples.index((ANY,'x'))
Thanks for helping
Add comment
Alex Naanou, 2007/04/05
sorry for not answering for so long... been a bit off ASPN for some time :)
well, in python 2.5 this just works :)
[(1,2),(3,0),(4,)].index((ANY, 0)) # returns 2
Add comment
|
|
|
|