Advertisement
Guest User

Untitled

a guest
Jul 15th, 2023
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. class TKey:
  2. def __init__(self, x, compare):
  3. self.value = x
  4. self.cmp = compare
  5.  
  6. def __le__(self, other):
  7. return self.cmp(self.value, other.value)
  8.  
  9. def __lt__(self, other):
  10. return self <= other and self.value != other.value
  11.  
  12. def __gt__(self, other):
  13. return not(self <= other)
  14.  
  15. def __ge__(self, other):
  16. return not(self < other)
  17.  
  18.  
  19. def main():
  20. straight_compare = lambda x, y: x <= y
  21. reverse_compare = lambda x, y: y <= x
  22. convert_to_key = lambda cmp: lambda x: TKey(x, cmp)
  23. print(sorted([1, 4, 35, 10, 8, 7, 9, 9, 12], key=convert_to_key(straight_compare))) # output: [1, 4, 7, 8, 9, 9, 10, 12, 35]
  24. print(sorted([1, 4, 35, 10, 8, 7, 9, 9, 12], key=convert_to_key(reverse_compare))) # output: [35, 12, 10, 9, 9, 8, 7, 4, 1]
  25.  
  26.  
  27. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement