SHARE
TWEET

Untitled

a guest Feb 21st, 2020 86 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from collections.abc import MutableSet
  2. import random
  3.  
  4. class RandSet(MutableSet):
  5.     def __init__(self, it=[]):
  6.         super().__init__()
  7.        
  8.         self.dict = {}
  9.         self.list = []
  10.  
  11.         self.extend(it)
  12.        
  13.     def add(self, item):
  14.         if item not in self.dict:
  15.             self.dict[item] = len(self.list)
  16.             self.list.append(item)
  17.  
  18.     def extend(self, seq):
  19.         for x in seq:
  20.             self.add(x)
  21.            
  22.     def discard(self, item):
  23.         if item in self.dict:
  24.             index = self.dict[item]
  25.             self.list[index], self.list[-1] = self.list[-1], self.list[index]
  26.             self.dict[self.list[index]] = index
  27.             del self.dict[self.list.pop()]
  28.  
  29.     def __repr__(self):
  30.         return repr(set(self))
  31.            
  32.     def __len__(self):
  33.         return len(self.list)
  34.  
  35.     def __iter__(self):
  36.         return iter(self.list)
  37.  
  38.     def __contains__(self, v):
  39.         return v in self.dict                
  40.  
  41.     def get_rand(self, r=random):
  42.         if self.list:
  43.             return self.list[r.randint(0,len(self.list)-1)]
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top