Create random_set.py

This commit is contained in:
marina 2023-07-31 10:50:05 -07:00 committed by GitHub
parent a50bbdf518
commit 50878d0b85
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

31
sets/random_set.py Normal file
View 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)