mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Create random_set.py
This commit is contained in:
parent
a50bbdf518
commit
50878d0b85
31
sets/random_set.py
Normal file
31
sets/random_set.py
Normal file
@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
import random
|
||||
|
||||
class RandomizedSet:
|
||||
|
||||
def __init__(self):
|
||||
self.set = []
|
||||
self.dict = {}
|
||||
|
||||
def insert(self, val: int) -> bool:
|
||||
if val in self.dict:
|
||||
return False
|
||||
self.set.append(val)
|
||||
self.dict[val] = len(self.set)
|
||||
return True
|
||||
|
||||
def remove(self, val: int) -> bool:
|
||||
if val in self.dict:
|
||||
index = self.dict[val]
|
||||
self.set[index] = self.set[-1]
|
||||
self.set.pop()
|
||||
del self.dict[val]
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_random(self) -> int:
|
||||
return random.choice(self.set)
|
||||
|
Loading…
x
Reference in New Issue
Block a user