Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. from random import randrange
  2. class RandomizedSet(object):
  3.  
  4. def __init__(self):
  5. """
  6. Initialize your data structure here.
  7. """
  8. self.list = list()
  9.  
  10.  
  11. def insert(self, val):
  12. """
  13. Inserts a value to the set. Returns true if the set did not already contain the specified element.
  14. :type val: int
  15. :rtype: bool
  16. """
  17. if val in self.list:
  18. return False
  19. else:
  20. self.list.append(val)
  21. return True
  22.  
  23.  
  24. def remove(self, val):
  25. """
  26. Removes a value from the set. Returns true if the set contained the specified element.
  27. :type val: int
  28. :rtype: bool
  29. """
  30. if val in self.list:
  31. self.list.remove(val)
  32. return True
  33. else:
  34. return False
  35.  
  36.  
  37. def getRandom(self):
  38. """
  39. Get a random element from the set.
  40. :rtype: int
  41. """
  42. n = len(self.list)
  43. return self.list[randrange(n)]
  44.  
  45.  
  46.  
  47.  
  48. # Your RandomizedSet object will be instantiated and called as such:
  49. # obj = RandomizedSet()
  50. # param_1 = obj.insert(val)
  51. # param_2 = obj.remove(val)
  52. # param_3 = obj.getRandom()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement