a rushed RandomizedSet impl

This commit is contained in:
Dan Buch 2023-10-25 20:15:43 -04:00
parent 6d523ad7c1
commit c8a4928ee8
Signed by: meatballhat
GPG Key ID: A12F782281063434
2 changed files with 46 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import copy import copy
import random
import typing import typing
import stdlib import stdlib
@ -393,3 +394,22 @@ def h_index(citations: list[int]) -> int:
break break
return last_qualified or 0 return last_qualified or 0
class RandomizedSet:
def __init__(self):
self._i: set[int] = set()
def insert(self, val: int) -> bool:
ok = val not in self._i
self._i.add(val)
return ok
def remove(self, val: int) -> bool:
if val in self._i:
self._i.remove(val)
return True
return False
def getRandom(self) -> int:
return next(iter(sorted(list(self._i), key=lambda _: random.random())))

View File

@ -331,3 +331,29 @@ def test_count_min_jumps_from_board(board: list[int], expected: int):
) )
def test_h_index(citations: list[int], expected: int): def test_h_index(citations: list[int], expected: int):
assert stuff.h_index(citations) == expected assert stuff.h_index(citations) == expected
def test_randomized_set():
inst = stuff.RandomizedSet()
assert inst.insert(1) is True
assert inst.remove(2) is False
assert inst.insert(2) is True
assert inst.getRandom() in (1, 2)
assert inst.remove(1) is True
assert inst.insert(2) is False
assert inst.getRandom() == 2
inst = stuff.RandomizedSet()
assert inst.insert(1) is True
assert inst.insert(10) is True
assert inst.insert(20) is True
assert inst.insert(30) is True
seen: set[int] = set()
for _ in range(100_000):
seen.add(inst.getRandom())
assert seen == {1, 10, 20, 30}