bdms.utils
#
Miscellaneous utilities needed by the rest of the package.
Module Contents#
Classes#
A set-like data structure that supports random sampling with constant time |
- class bdms.utils.RandomizedSet(items=())#
A set-like data structure that supports random sampling with constant time complexity.
Example
>>> import bdms
Initialize with any iterable of hashable items.
>>> rs = bdms.utils.RandomizedSet("abc") >>> rs RandomizedSet('a', 'b', 'c') >>> len(rs) 3
Add an item.
>>> rs.add('d') >>> rs RandomizedSet('a', 'b', 'c', 'd') >>> len(rs) 4
Choose a random item.
>>> rs.choice(seed=0) 'd'
Remove an item.
>>> rs.remove('a') >>> rs RandomizedSet('d', 'b', 'c')
Iterate over the items.
>>> for item in rs: ... print(item) d b c
Reverse iterate over the items.
>>> for item in reversed(rs): ... print(item) c b d
- Parameters:
items (Iterable[Hashable]) – Items to initialize the set with.
- add(item)#
Add an item to the set.
- Parameters:
item (Hashable) – The item to add.
- remove(item)#
Remove an item from the set.
- Parameters:
item (Hashable) – The item to remove.
- Raises:
KeyError – If the item is not in the set.
- choice(seed=None)#
Randomly sample an item from the set.
- Parameters:
seed (int | Generator | None) – A seed to initialize the random number generation. If
None
, then fresh, unpredictable entropy will be pulled from the OS. If anint
, then it will be used to derive the initial state. If anumpy.random.Generator
, then it will be used directly.- Returns:
The sampled item.
- Return type:
Any