2025-09-29
bag:
The next step is to draw up a list of function names, method names, and operator symbols that meet the descriptions of these operations
Examples include:
- add
- clear
- count
- for ...
- in
- isEmpty
- len
- remove
- str
- +
- ==b and c refer to bagsb.clear() # Make the bag empty
for item in range(10): # Add 10 numbers to it
b.add(item)
print(b) # Print the contents (a string)
print(4 in b) # Is 4 in the bag?
print(b.count(2)) # 1 instance of 2 in the bag
c = b + b # Contents replicated in a new bag
print(len(c)) # 20 numbers
for item in c: # Print them all individually
print(item)
for item in range(10): # Remove half of them
c.remove(item)
print(c == b) #Should be the same contents now| User’s Bag Operation | Method in a Bag Class |
|---|---|
| b = |
init(self, sourceCollection=None) |
| b.add(item) | add(self, item) |
| b.clear() | clear(self) |
| b.count(item) | count(self, item) |
| b.isEmpty() | isEmpty(self) |
| b.remove(item) | remove(self, item) |
| len(b) | __len__(self) |
| str(b) | __str__(self) |
| for item in b | __iter__(self). |
| item in b | __contains__(self, item) Not needed if __iter__ is included |
| b1 + b2 | __add__(self, other) |
| b == anyObject | __eq__(self, other) |
<class name> is used in the table to indicate that this can be the name of any implementing bag class:
_init_remove method might raise a KeyError if the target item is not in the bagremove method:pass or return statement:
pass statement is used in the mutator methods that return no value, whereas each accessor method returns a simple default value, such as False, 0, or None"""
File: baginterface.py
Author: Ken Lambert
"""
class BagInterface(object):
"""Interface for all bag types."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self, which includes the
contents of sourceCollection, if it’s present."""
pass
# Accessor methods
def isEmpty(self):
"""Returns True if len(self) == 0,
or False otherwise."""
return True
def __len__(self):
"""Returns the number of items in self."""
return 0
def __str__(self):
"""Returns the string representation of self."""
return ""
def __iter__(self):
"""Supports iteration over a view of self."""
return None
def __add__(self, other):
"""Returns a new bag containing the contents
of self and other."""
return None
def __eq__(self, other):
"""Returns True if self equals other,
or False otherwise."""
return False
def count(self, item):
"""Returns the number of instances of item in self."""
return 0
# Mutator methods
def clear(self):
"""Makes self become empty."""
pass
def add(self, item):
"""Adds item to self."""
pass
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item in not in self.
Postcondition: item is removed from self."""
pass