Advertisement
Guest User

bag

a guest
Mar 18th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Feb 19 15:48:58 2019
  4.  
  5. @author: Zsu
  6. """
  7.  
  8.  
  9. class Bag:
  10. # creates a new, empty Bag
  11. def __init__(self):
  12. self.__bag = []
  13.  
  14. # adds a new element to the Bag
  15. # O(1)
  16. def add(self, e):
  17. self.__bag.append(e)
  18.  
  19. # removes one occurrence of an element from a Bag
  20. # returns True if an element was actually removed (the Bag contained the element e), or False if nothing was removed
  21. # O(n)
  22. def remove(self, e):
  23. if self.search(e):
  24. self.__bag.remove(e)
  25. return True
  26.  
  27. return False
  28.  
  29. # searches for an element e in the Bag
  30. # returns True if the Bag contains the element, False otherwise
  31. # O(n)
  32. def search(self, e):
  33. return e in self.__bag
  34.  
  35. # counts and returns the number of times the element e appears in the bag
  36. # O(n)
  37. def nrOccurrences(self, e):
  38. return self.__bag.count(e)
  39.  
  40. # returns the size of the Bag (the number of elements)
  41. # O(1)
  42. def size(self):
  43. return len(self.__bag)
  44.  
  45. # returns True if the Bag is empty, False otherwise
  46. # O(1)
  47. def isEmpty(self):
  48. return not self.__bag
  49.  
  50. # returns a BagIterator for the Bag
  51. # O(1)
  52. def iterator(self):
  53. return BagIterator(self.__bag)
  54.  
  55.  
  56. class BagIterator:
  57. #creates an iterator for the Bag b, set to the first element of the bag, or invalid if the Bag is empty
  58. def __init__(self, b):
  59. self.__bag = b
  60. self.__i = 0
  61.  
  62. # returns True if the iterator is valid
  63. # O(1)
  64. def valid(self):
  65. return self.__i < len(self.__bag)
  66.  
  67. # returns the current element from the iterator.
  68. # throws ValueError if the iterator is not valid
  69. # O(1)
  70. def getCurrent(self):
  71. if not self.valid():
  72. raise ValueError("Iterator not valid")
  73.  
  74. return self.__bag[self.__i]
  75.  
  76. # moves the iterator to the next element
  77. # throws ValueError if the iterator is not valid
  78. # O(1)
  79. def next(self):
  80. if not self.valid():
  81. raise ValueError("Iterator not valid")
  82.  
  83. self.__i += 1
  84.  
  85. # sets the iterator to the first element from the Bag
  86. # O(1)
  87. def first(self):
  88. self.__i = 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement