5 ms·
So this only works for numbers right?
by lpapez 5y ago
So this only works for numbers right?
- contravariant 5y agoIf they use math.inf then yeah probably. You might be able to create an object that always compares as less than something, using something like: class Bottom: def __le__(self, other): return True def __lt__(self, other): return True though use this with care.
- eesmith 5y agoOnly some numbers. As is, my implementation requires objects where "<" and "<=" are meaningful, and it requires that a comparison to -math.inf is also meaningful. For example, it won't work with complex numbers, first because they cannot be compared to -math.inf: >>> list(monotonic_direct([1j, 2j, 4j])) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "monotonic.py", line 40, in monotonic_direct test = prev_value <= value TypeError: '<=' not supported between instances of 'float' and 'complex' and second because Python doesn't support an ordering for complex numbers: >>> 1j < 2j Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '<' not supported between instances of 'complex' and 'complex' As I mentioned, it's possible to replace the sentinel -math.inf with something that starts with seq[0]. This would allow strings and orderable objects. This is left as an exercise for the reader. ;)