Re:Pythonic monotonic
by lpapez on Friday August 13, 2021 @08:37AM
(#28168127)
So this only works for numbers right?
[ Parent
| on HN ]
Only 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. ;)
Re:Pythonic monotonic
by contravariant on Friday August 13, 2021 @09:03AM
(#28168344)
If 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.