Need assistance with this assignment this python code

I have completed the code for my class down to part 3 where I need assistance. Also, I am getting errors when trying to compile it. I attach will the errors and the expected results and the guidance I was given for this assignment.

Author: Derrf Seitz

This program exercises bags.

The following files must be in the same folder:

# <your name>

# Replace <your name> with your name.
# Replace any "<your code>" comments with your own code statement(s)
# to accomplish the specified task.

# We can use a simple "for" loop to traverse a collection.
# We will call this "regular iteration" or, for brevity, simply "iteration".
# During a regular iteration, you cannot add or remove an item from a framework collection!
# Breaking this rule will cause an immediate exception to occur.
# The exception will display a message and terminate (crash) your program!
# The displayed message is: "Illegal modification of backing store".
# Note that you can update item attributes during iteration.
# Later in this course, we will learn about special "list iterators".
# Unlike regular iterators, list iterators allow modification (add and remove) during iteration.

from arraybag import ArrayBag
from ball import Ball
from linkedbag import LinkedBag
from node import Node

# Part 1:
# This function takes a bag that has red and blue balls in it
# and moves the balls to two other bags: one to hold the red
# balls and one to hold the blue balls. Every red ball is inflated
# to twice its radius before being added to its new bag.
# Preconditions:
#   bag - an ArrayBag containing zero or more red and blue Ball objects. 
# Postconditions:
#   returns - a bag containing the doubled radius red balls and
#             a bag containing the blue balls.
#   The original bag should be emptied.
def distributeBag(bag):
   redBag = ArrayBag()
   blueBag = ArrayBag()

   # Move the balls to the appropriate bags:

   for x in bag:
       if x.getColor() == "red":
       elif x.getColor() == "blue":
   # Return the 2 bags:
   return (redBag, blueBag)

# Part 2:
# This function prints the items in a bag, each on a separate line.
def printBag(bag):
   for x in bag:
       if bag.isEmpty():

# Part 3:
# This function removes duplicate items from a bag.
# Postconditions:
#   Any item that appears more than once will be reduced to a single occurrence.
#   Example: If there were 3 of item A, there will only be 1 of item A remaining.
def removeDuplicates(bag):
   # <your code>

# Test 1:
   print("Test 1:")
bag1 = ArrayBag([Ball("red", 10),
               Ball("red", 11),
               Ball("red", 12),
               Ball("blue", 15),
               Ball("blue", 15),
               Ball("blue", 15)])
print("Original mixed bag:")
redBag, blueBag = distributeBag(bag1)
print("Red bag:")
print("Blue bag:")
print("Final mixed bag:")

# Test 2:
print("Test 2:")
bag2 = ArrayBag([Ball("red", 201),
               Ball("red", 201),
               Ball("red", 202),
               Ball("red", 202)])
print("Original mixed bag:")
redBag, blueBag = distributeBag(bag2)
print("Red bag:")
print("Blue bag:")
print("Final mixed bag:")

# Test 3:
print("Test 3:")
bag3 = ArrayBag()
print("Original mixed bag:")
redBag, blueBag = distributeBag(bag3)
print("Red bag:")
print("Blue bag:")
print("Final mixed bag:")

# Test 4:
print("Test 4:")
bag4 = LinkedBag(["apple",
print("Original bag with duplicates:")
print("Bag after removing duplicates:")

Expected Outcome part 1

Expected Outcome part 2

Activity Guidance Part 1

Activity Guidance Part 2

Activity Guidance Part 3

Errors I am getting

Was asked to share the code


File: Author: Ken Lambert, copyright 2015, 2020 Used by permission. “”

from arrays import Array from abstractbag import AbstractBag

class ArrayBag(AbstractBag): “””An array-based bag implementation.”””

# Class variables
INTERFACE = "BagInterface"

# Constructor
def __init__(self, sourceCollection = None):
    """Sets the initial state of self, which includes the
    contents of sourceCollection, if it's present."""
    self.items = Array(ArrayBag.DEFAULT_CAPACITY)
    AbstractBag.__init__(self, sourceCollection)

# Accessor methods
def __iter__(self):
    """Supports iteration over a view of self."""
    modCount = self.getModCount()
    cursor = 0
    while cursor < len(self):
        yield self.items[cursor]
        if modCount != self.getModCount():
            raise AttributeError("Illegal modification of backing store")
        cursor += 1

# Mutator methods
def add(self, item):
    """Adds item to self."""
    # Resize array if necessary:
    if len(self) == len(self.items):
        tempArray = Array(len(self) * 2)
        for i in range(len(self)):
            tempArray[i] = self.items[i]
        self.items = tempArray
    self.items[len(self)] = item
    self.size += 1

def clear(self):
    """Makes self become empty."""
    self.size = 0
    self.modCount = 0
    self.items = Array(ArrayBag.DEFAULT_CAPACITY)

def remove(self, item):
    """Precondition: item is in self.
    Raises: KeyError if item in not in self.
    Postcondition: item is removed from self."""
    # 1. Check precondition and raise an exception if necessary:
    if not item in self:
        raise KeyError(str(item) + " not in bag")
    # 2. Search for index of target item:
    targetIndex = 0
    for targetItem in self:
        if targetItem == item:
        targetIndex += 1
    # 3. Shift items to the right of target left by one position:
    for i in range(targetIndex, len(self) - 1):
        self.items[i] = self.items[i + 1]
    # 4. Decrement logical size:
    self.size -= 1
    # 5. Resize array if necessary:
    if len(self) <= .25 * len(self.items) and 
       ArrayBag.DEFAULT_CAPACITY <= len(self.items) // 2:
        tempArray = Array(len(self.items) // 2)
        for i in range(len(self)):
            tempArray[i] = self.items[i]
        self.items = tempArray

Leave a Comment