mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
Create random_set.py
This commit is contained in:
parent
a50bbdf518
commit
50878d0b85
1 changed files with 31 additions and 0 deletions
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…
Add table
Add a link
Reference in a new issue