Question

Please code in Python Revise the AbstractBag class so that it behaves as a subclass of...

Please code in Python

Revise the AbstractBag class so that it behaves as a subclass of AbstractCollection provided in the file abstractcollection.py.



Abstractcollection.py code:

class AbstractCollection(object):

    """An abstract collection implementation."""

    # Constructor

    def __init__(self, sourceCollection = None):

        """Sets the initial state of self, which includes the

        contents of sourceCollection, if it's present."""

        self.size = 0

        if sourceCollection:

            for item in sourceCollection:

                self.add(item)

    # Accessor methods

    def isEmpty(self):

        """Returns True if len(self) == 0, or False otherwise."""

        return len(self) == 0

    

    def __len__(self):

        """Returns the number of items in self."""

        return self.size

    def __str__(self):

        """Returns the string representation of self."""

        return "[" + ", ".join(map(str, self)) + "]"

    def __add__(self, other):

        """Returns a new bag containing the contents

        of self and other."""

        result = type(self)(self)

        for item in other:

            result.add(item)

        return result

    def __eq__(self, other):

        """Returns True if self equals other,

        or False otherwise."""

        if self is other: return True

        if type(self) != type(other) or \

           len(self) != len(other):

            return False

        otherIter = iter(other)

        for item in self:

            if item != next(otherIter):

                return False

        return True

    def count(self, item):

        """Returns the number of instances of item in self."""

        total = 0

        for nextItem in self:

            if nextItem == item:

                total += 1

        return total

Abstractbag.py Code:

from abstractcollection import AbstractCollection

class AbstractBag(AbstractCollection):

    """An abstract bag implementation."""

    # Constructor

    def __init__(self, sourceCollection = None):

        AbstractCollection__init__(self, sourceColletion)

        """Sets the initial state of self, which includes the

        contents of sourceCollection, if it's present."""

        self.size = 0

        if sourceCollection:

            for item in sourceCollection:

                self.add(item)

    # Accessor methods

    def isEmpty(self):

        """Returns True if len(self) == 0, or False otherwise."""

        return len(self) == 0

    def __len__(self):

        """Returns the number of items in self."""

        return self.size

    def __str__(self):

        """Returns the string representation of self."""

        return "{" + ", ".join(map(str, self)) + "}"

    def __add__(self, other):

        """Returns a new bag containing the contents

        of self and other."""

        result = type(self)(self)

        for item in other:

            result.add(item)

        return result

    def __eq__(self, other):

        """Returns True if self equals other,

        or False otherwise."""

        if self is other: return True

        if type(self) != type(other) or \

           len(self) != len(other):

            return False

        for item in self:

            if self.count(item) != other.count(item):

                return False

        return True

    def count(self, item):

        """Returns the number of instances of item in self."""

        total = 0

        for nextItem in self:

            if nextItem == item:

                total += 1

        return total

0 0
Add a comment Improve this question Transcribed image text
Answer #1

# do comment if any problem arises

# Code

from abstractcollection import AbstractCollection


class AbstractBag(AbstractCollection):

    """An abstract bag implementation."""

    # Constructor

    def __init__(self, sourceCollection=None):

        super().__init__(sourceCollection=sourceCollection)

    # Accessor methods

    def isEmpty(self):

        """Returns True if len(self) == 0, or False otherwise."""

        return super().isEmpty()

    def __len__(self):

        """Returns the number of items in self."""

        return super().__len__()

    def __str__(self):

        """Returns the string representation of self."""

        return super().__str__()

    def __add__(self, other):

        """Returns a new bag containing the contents

        of self and other."""

        return super().__add__(other)

    def __eq__(self, other):

        """Returns True if self equals other,

        or False otherwise."""

        return super().__eq__(other)

    def count(self, item):

        """Returns the number of instances of item in self."""

        return super().count(item)

Screenshot:

Add a comment
Know the answer?
Add Answer to:
Please code in Python Revise the AbstractBag class so that it behaves as a subclass of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python 3+ Adjust the following code so the two errors below are non-present: 1. __init__() :...

    Python 3+ Adjust the following code so the two errors below are non-present: 1. __init__() : Since Pizza object don't have it's own set() datastructure, the toppings in the pizza object are manimupated from out of the object. (-1.0) 2. __eq__() : How about "self.toppings == other.toppings" rather than "self.toppings - other.toppin == set())". Code: ## Program 1 ## --------------------------------- class Pizza: def __init__(self, s='M', top=set()): self.setSize(s) self.toppings = top def setSize(self, s): self.size = s def getSize(self): return self.size...

  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

  • In this part, you will complete the code to solve a maze.

    - Complete the code to solve a maze- Discuss related data structures topicsProgramming-----------In this part, you will complete the code to solve a maze.Begin with the "solveMaze.py" starter file.This file contains comment instructions that tell you where to add your code.Each maze resides in a text file (with a .txt extension).The following symbols are used in the mazes:BARRIER = '-' # barrierFINISH = 'F' # finish (goal)OPEN = 'O' # open stepSTART = 'S' # start stepVISITED = '#' #...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • Use your Food class, utilities code, and sample data from Lab 1 to complete the following...

    Use your Food class, utilities code, and sample data from Lab 1 to complete the following Tasks. def average_calories(foods):     """     -------------------------------------------------------     Determines the average calories in a list of foods.     foods is unchanged.     Use: avg = average_calories(foods)     -------------------------------------------------------     Parameters:         foods - a list of Food objects (list of Food)     Returns:         avg - average calories in all Food objects of foods (int)     -------------------------------------------------------     """ your code here is the...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • Python code that sorts books

    class Book:    def __init__(self,id,bookName,authorName,nextNode=None):         self.id = id         self.bookName = bookName         self.authorName = authorName         self.nextNode = nextNode    def getId(self):        return self.id     def getBookName(self):        return self.bookName    def getAuthorName(self):        return self.authorName    def getNextNode(self):        return self.nextNode       def setNextNode(self,val):         self.nextNode = val   class LinkedList:    def __init__(self,head = None):         self.head = head         self.size = 0     def getSize(self):        return self.size    def AddBookToFront(self,newBook):         newBook.setNextNode(self.head)         self.head = newBook         self.size+=1     def DisplayBook(self):         curr = self.head        while curr:            print(curr.getId(),curr.getBookName(),curr.getAuthorName())              curr = curr.getNextNode()    def RemoveBookAtPosition(self,n):         prev = None         curr = self.head         curPos = 0         while curr:            if curPos == n:                if prev:                     prev.setNextNode(curr.getNextNode())                else:                     self.head = curr.getNextNode()                 self.size = self.size - 1                 return True                  prev = curr             curr = curr.getNextNode()              curPos = curPos + 1          return False     def AddBookAtPosition(self,newBook,n):         curPos = 1         if n == 0:             newBook.setNextNode(self.head)             self.head = newBook             self.size+=1             return         else:             currentNode = self.head            while currentNode.getNextNode() is not None:                if curPos == n:                     newBook.setNextNode(currentNode.getNextNode())                     currentNode.setNextNode(newBook)                     self.size+=1                     return                 currentNode = currentNode.getNextNode()                 curPos = curPos + 1             if curPos == n:                 newBook.setNextNode(None)                 currentNode.setNextNode(newBook)                 self.size+=1             else:                print("cannot add",newBook.getId(),newBook.getBookName(),"at that position")    def SortByAuthorName(self):        for i in range(1,self.size):             node1 = self.head             node2 = node1.getNextNode()            while node2 is not None:                if node1.authorName > node2.authorName:                     temp = node1.id                     temp2 = node1.bookName                     temp3 = node1.authorName                     node1.id = node2.id                     node1.bookName = node2.bookName                     node1.authorName = node2.authorName                     node2.id = temp                     node2.bookName = temp2                     node2.authorName = temp3                 node1 = node1.getNextNode()                 node2 = node2.getNextNode()     myLinkedList = LinkedList() nodeA = Book("#1","cool","Isaac") nodeB = Book("#2","amazing","Alfred") nodeC = Book("#3","hello","John") nodeD = Book("#4","why","Chase") nodeE = Book("#5","good","Mary") nodeF = Book("#6","hahaha","Radin") myLinkedList.AddBookToFront(nodeA) myLinkedList.AddBookToFront(nodeB) myLinkedList.AddBookToFront(nodeC) myLinkedList.AddBookAtPosition(nodeD,1) myLinkedList.AddBookAtPosition(nodeE,1) myLinkedList.AddBookAtPosition(nodeF,1) myLinkedList.RemoveBookAtPosition(2) myLinkedList.RemoveBookAtPosition(2) myLinkedList.DisplayBook() myLinkedList.SortByAuthorName()print(myLinkedList.getSize())...

  • reate a class called Person with the following attributes: name - A string representing the person's...

    reate a class called Person with the following attributes: name - A string representing the person's name age - An int representing the person's age in years As well as appropriate __init__ and __str__ methods, include the following methods: get_name(self) - returns the name of the person get_age(self) - returns the age of the person set_name(self, new_name) - sets the name for the person set_age(self, new_age) - sets the age for the person is_older_than(self, other) - returns True if this...

  • Implement the class MaxHeapPriorityQueue as a heap with the following operations: • MaxHeapPriorityQueue() creates a new...

    Implement the class MaxHeapPriorityQueue as a heap with the following operations: • MaxHeapPriorityQueue() creates a new heap that is empty. It needs no parameters and returns nothing. Note that as discussed in the video lecture, the index range of the array implementation of a heap is 1:n, NOT 0:n-1 • parent(index) returns the value of the parent of heap[index]. index is between 1 and the size of the heap. If index<=1 or index>size of the heap, it returns None •...

  • Implement the class MaxHeapPriorityQueue as a heap with the following operations using python: - ...

    Implement the class MaxHeapPriorityQueue as a heap with the following operations using python: - MaxHeapPriorityQueue() creates a new heap that is empty. It needs no parameters and returns nothing. - parent(index) returns the value of the parent of heap[index]. index is between 1 and the size of the heap. If index<=1 or index>size of the heap, it returns None - leftChild(index) returns the value of the left child of heap[index], returns None if there is no value - rightChild(index) returns...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT