Re:What's New in Python 3.11?
by rad_gruchalski on Monday June 27, 2022 @02:10AM
(#31891137)
How about a more complex type? Something like a custom class instance?
[ Parent
| on HN ]
Re:What's New in Python 3.11?
by paskozdilar on Monday June 27, 2022 @02:23AM
(#31891225)
As long as your type is isomorphic to an array, you can implement __len__() and __getitem__(i) and bisect will still work:
>>> class C:
... def __len__(self):
... return 10
... def __getitem__(self, i):
... if i >= 10:
... raise IndexError('out of range')
... return i+1
...
>>> c = C()
>>> import bisect
>>> bisect.bisect_left(c, 1)
0
>>> bisect.bisect_left(c, 4)
3Or you can implement a binary search in your type's __contains__ and just use `"foo" in c`
Re:What's New in Python 3.11?
by paskozdilar on Monday June 27, 2022 @05:23AM
(#31892277)
You can do that too, using the bisect, provided you have the __len__ and __getitem__ implemented:
class C:
def __len__(self): ...
def __getitem__(self, i): ...
def __contains__(self, x):
i = bisect.bisect_left(self, x)
return i < len(self) and self[i] == x
At that point it's just syntactic sugar.
Re:What's New in Python 3.11?
by rad_gruchalski on Monday June 27, 2022 @02:38AM
(#31891313)
Thanks!