Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hannestyden
Last active December 26, 2023 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hannestyden/7320c2f245883a0a41f34764c63876c9 to your computer and use it in GitHub Desktop.
Save hannestyden/7320c2f245883a0a41f34764c63876c9 to your computer and use it in GitHub Desktop.
Python POGS - Principle of greatest surprise
import sys
from functools import cmp_to_key
def p(data, label=None):
if label:
print(label, end=": ", file=sys.stderr)
print(data, file=sys.stderr)
return data
def key(element):
p(element, "key")
return element
def cmp(a, b):
p((a, b), "cmp")
return a - b
# https://github.com/python/cpython/blob/48c49739f5502fc7aa82f247ab2e4d7b55bdca62/Lib/functools.py#L209C1-L224C13
class Cmp(object):
__slots__ = ["obj"]
def __init__(self, obj):
p((self, obj), "Cmp.__init__")
self.obj = obj
def __lt__(self, other):
p((self.obj, other.obj), "Cmp.__lt__")
return self.cmp(self.obj, other.obj) < 0
def __gt__(self, other):
p((self.obj, other.obj), "Cmp.__gt__")
return self.cmp(self.obj, other.obj) > 0
def __eq__(self, other):
p((self.obj, other.obj), "Cmp.__eq__")
return self.cmp(self.obj, other.obj) == 0
def __le__(self, other):
p((self.obj, other.obj), "Cmp.__le__")
return self.cmp(self.obj, other.obj) <= 0
def __ge__(self, other):
p((self.obj, other.obj), "Cmp.__ge__")
return self.cmp(self.obj, other.obj) >= 0
def cmp(self, a, b):
p((a, b), "Cmp.cmp")
return a - b
__hash__ = None
l = [5, 1, 4, 2, 3]
print(l)
print("sorted with key")
print(sorted(l, key=key))
print("sorted with cmp_to_key(cmp)")
print(sorted(l, key=cmp_to_key(cmp)))
print("sorted with Cmp")
print(sorted(l, key=Cmp))
key: 5
key: 1
key: 4
key: 2
key: 3
cmp: (1, 5)
cmp: (4, 1)
cmp: (4, 5)
cmp: (4, 1)
cmp: (2, 4)
cmp: (2, 1)
cmp: (3, 4)
cmp: (3, 2)
Cmp.__init__: (<__main__.Cmp object at 0x105143c40>, 5)
Cmp.__init__: (<__main__.Cmp object at 0x105143be0>, 1)
Cmp.__init__: (<__main__.Cmp object at 0x105143b80>, 4)
Cmp.__init__: (<__main__.Cmp object at 0x105143b20>, 2)
Cmp.__init__: (<__main__.Cmp object at 0x105143b50>, 3)
Cmp.__lt__: (1, 5)
Cmp.cmp: (1, 5)
Cmp.__lt__: (4, 1)
Cmp.cmp: (4, 1)
Cmp.__lt__: (4, 5)
Cmp.cmp: (4, 5)
Cmp.__lt__: (4, 1)
Cmp.cmp: (4, 1)
Cmp.__lt__: (2, 4)
Cmp.cmp: (2, 4)
Cmp.__lt__: (2, 1)
Cmp.cmp: (2, 1)
Cmp.__lt__: (3, 4)
Cmp.cmp: (3, 4)
Cmp.__lt__: (3, 2)
Cmp.cmp: (3, 2)
[5, 1, 4, 2, 3]
sorted with key
[1, 2, 3, 4, 5]
sorted with cmp_to_key(cmp)
[1, 2, 3, 4, 5]
sorted with Cmp
[1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment