python language: infimum and supremum of integers

Mel Wilson mwilson at the-wire.com
Thu Apr 24 11:01:48 EDT 2003


In article <b87iqe$e9v$1 at slb4.atl.mindspring.net>,
"Andrew Dalke" <adalke at mindspring.com> wrote:
>Charlie Reiman:
>> Are there any dangers in something like this:
>>
>> a = [1, infimum, infimum]
>> a.sort()
>>
>> Should the __cmp__ methods return 0 for equality (identity, in this
>> case)?
>
>As Alex pointed out, it should.
>
>However, I recall a post by Tim Peters some years ago saying
>that he fixed the sort code so it would finish, even in the face of
>absurdities like this.
>
>But I'm too lazy to find the post, or even test the code.  ;)

I've been playing:

#=======================================

"""limitcases.py
Provides objects which compare less-than and greater-than any other object.
Useful for sentinels, or for initial values in maximum- or minimum-finding
routines.
"""

class LowLimit:
    "Instances of LowLimit compare < any object except each other."
    def __cmp__ (self, other):
        if isinstance (other, LowLimit):
            return 0
        return -1

    def __hash__ (self):
        return id (LowLimit)
# class LowLimit


class HighLimit:
    "Instances of HighLimit compare > any object except each other."
    def __cmp__ (self, other):
        if isinstance (other, HighLimit):
            return 0
        return 1

    def __hash__ (self):
        return id (HighLimit)
# class HighLimit


if __name__ == '__main__':
    print LowLimit()
    print HighLimit()
    print

    # An application can provide its own printable representation.
    LowLimit.__str__ = lambda (x): "-Infinity"
    HighLimit.__str__ = lambda (x): "+Infinity"

    x = [1, HighLimit(), 2, LowLimit(), 0, HighLimit(), LowLimit()]
    x.sort()
    print 'X = ',
    for v in x:
        print v,
    print
    print
    print'X:', x
    print

#=======================================


   I hope I'm not spoiling the game for people who should be
learning.  I should probably look up singleton classes which
LowLimit and HighLimit should probably be.

        Regards.        Mel.




More information about the Python-list mailing list