source: utilitiespy/tudelft/utilities/tools/comparator.py@ 1237

Last change on this file since 1237 was 1230, checked in by wouter, 2 weeks ago

#388 added PriorityQueue and Comparator to utilities package, simulating java classes with same name

File size: 2.5 KB
RevLine 
[1230]1from abc import ABC, abstractmethod
2from typing import TypeVar, Generic, Any
3
4T=TypeVar("T")
5
6class Comparator(Generic[T]):
7
8 @abstractmethod
9 def compare(self, o1:T, o2:T)-> int:
10 '''
11 Compares its two arguments for order. Returns a negative integer,
12 zero, or a positive integer as the first argument is less than, equal
13 to, or greater than the second.<p>
14
15 The implementor must ensure that {@code sgn(compare(x, y)) ==
16 -sgn(compare(y, x))} for all {@code x} and {@code y}. (This
17 implies that {@code compare(x, y)} must throw an exception if and only
18 if {@code compare(y, x)} throws an exception.)<p>
19
20 The implementor must also ensure that the relation is transitive:
21 {@code ((compare(x, y)>0) && (compare(y, z)>0))} implies
22 {@code compare(x, z)>0}.<p>
23
24 Finally, the implementor must ensure that {@code compare(x, y)==0}
25 implies that {@code sgn(compare(x, z))==sgn(compare(y, z))} for all
26 {@code z}.<p>
27
28 It is generally the case, but <i>not</i> strictly required that
29 {@code (compare(x, y)==0) == (x.equals(y))}. Generally speaking,
30 any comparator that violates this condition should clearly indicate
31 this fact. The recommended language is "Note: this comparator
32 imposes orderings that are inconsistent with equals."<p>
33
34 In the foregoing description, the notation
35 {@code sgn(}<i>expression</i>{@code )} designates the mathematical
36 <i>signum</i> function, which is defined to return one of {@code -1},
37 {@code 0}, or {@code 1} according to whether the value of
38 <i>expression</i> is negative, zero, or positive, respectively.
39
40 @param o1 the first object to be compared.
41 @param o2 the second object to be compared.
42 @return a negative integer, zero, or a positive integer as the
43 first argument is less than, equal to, or greater than the
44 second.
45 @raises ValueError if an argument is null and this
46 comparator does not permit null arguments
47 @raises ClassCastException if the arguments' types prevent them from
48 being compared by this comparator.
49
50 '''
51 pass
52
53
54class DefaultComparator(Comparator[Any]):
55 def compare(self, o1:Any, o2:Any)-> int:
56 return -1 if o1<o2 else 1 if o1>o2 else 0
57
58
Note: See TracBrowser for help on using the repository browser.