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.

    """
File: useBag.py
Author: Derrf Seitz

This program exercises bags.

The following files must be in the same folder:
 abstractcollection.py
 abstractbag.py
 arraybag.py
 arrays.py
 ball.py
 linkedbag.py
 node.py
"""

# <your name>

# Replace <your name> with your name.
# Replace any "<your code>" comments with your own code statement(s)
# to accomplish the specified task.
# DO NOT CHANGE ANY OTHER CODE.

# IMPORTANT NOTE:
# 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":
           redBag.add(x)
       elif x.getColor() == "blue":
               blueBag.add(x)
               bag.clear()
   # 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:
       print(x)
       if bag.isEmpty():
           print("empty")
           print()

# 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:")
printBag(bag1)
redBag, blueBag = distributeBag(bag1)
print("Red bag:")
printBag(redBag)
print("Blue bag:")
printBag(blueBag)
print("Final mixed bag:")
printBag(bag1)

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

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

# Test 4:
print("Test 4:")
bag4 = LinkedBag(["apple",
                 "apple",
                 "banana",
                 "kiwi",
                 "cantaloupe",
                 "pear",
                 "banana",
                 "orange",
                 "orange",
                 "cantaloupe",
                 "apple",
                 "lemon",
                 "lime",
                 "lime"])
print("Original bag with duplicates:")
printBag(bag4)
removeDuplicates(bag4)
print("Bag after removing duplicates:")
printBag(bag4)

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 arraybag.py code

"""

File: arraybag.py 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
DEFAULT_CAPACITY = 10
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
    self.incModCount()

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:
            break
        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
    self.incModCount()
    # 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