Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Tue Feb 19 15:48:58 2019
- @author: Zsu
- """
- class Bag:
- # creates a new, empty Bag
- def __init__(self):
- self.__bag = []
- # adds a new element to the Bag
- # O(1)
- def add(self, e):
- self.__bag.append(e)
- # removes one occurrence of an element from a Bag
- # returns True if an element was actually removed (the Bag contained the element e), or False if nothing was removed
- # O(n)
- def remove(self, e):
- if self.search(e):
- self.__bag.remove(e)
- return True
- return False
- # searches for an element e in the Bag
- # returns True if the Bag contains the element, False otherwise
- # O(n)
- def search(self, e):
- return e in self.__bag
- # counts and returns the number of times the element e appears in the bag
- # O(n)
- def nrOccurrences(self, e):
- return self.__bag.count(e)
- # returns the size of the Bag (the number of elements)
- # O(1)
- def size(self):
- return len(self.__bag)
- # returns True if the Bag is empty, False otherwise
- # O(1)
- def isEmpty(self):
- return not self.__bag
- # returns a BagIterator for the Bag
- # O(1)
- def iterator(self):
- return BagIterator(self.__bag)
- class BagIterator:
- #creates an iterator for the Bag b, set to the first element of the bag, or invalid if the Bag is empty
- def __init__(self, b):
- self.__bag = b
- self.__i = 0
- # returns True if the iterator is valid
- # O(1)
- def valid(self):
- return self.__i < len(self.__bag)
- # returns the current element from the iterator.
- # throws ValueError if the iterator is not valid
- # O(1)
- def getCurrent(self):
- if not self.valid():
- raise ValueError("Iterator not valid")
- return self.__bag[self.__i]
- # moves the iterator to the next element
- # throws ValueError if the iterator is not valid
- # O(1)
- def next(self):
- if not self.valid():
- raise ValueError("Iterator not valid")
- self.__i += 1
- # sets the iterator to the first element from the Bag
- # O(1)
- def first(self):
- self.__i = 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement