SlideShare a Scribd company logo
1 of 10
Download to read offline
Adding methods to the ListBag class
In the file ListBag.py, add the methods described below to the ListBag class, and then add code
to test these methods. You should not add any new instance variables (fields) to the class.
def isEmpty(self)
This method should return True if the ListBag is empty, and False otherwise.
def numOccur(self, item)
This method should return the number of times that the parameter item occurs in the called
ListBag. For example, if b1 represents the bag
{7, 5, 3, 5, 7, 2, 7}, then b1.numOccur(2) should return 1, b1.numOccur(7) should return 3, and
b1.numOccur(20) should return 0.
def addItems(self, other)
This method should attempt to add to the called ListBag all of the items found in the parameter
other. As a result, your method should use method calls to access the internals of that bag. See
our implementation of the containsAll() method for an example of this.
def equals(self, other)
This method should determine if the called ListBag is equal to the parameter other. Two bags are
equal if they contain the same items. The location of the items in the bags does not matter (e.g.,
{5, 6, 6, 7} is equal to {7, 6, 5, 6}), but bags that are equal must have the same number of
occurrences of each item (e.g., {5, 6, 6, 7} is not equal to {5, 6, 7}). The method should return
True if the two bags are equal, and False otherwise (including cases in which the parameter is
None). Your method should use method calls to access the internals of that bag. See our
implementation of the containsAll() method for an example of this. You are strongly encouraged
you to have yourequalsmethod take advantage of one of the other methods that you are
implementing for this problem.
def unionWith(self, other)
This method should create and return an ListBag containing one occurrence of any item that is
found in either the called object or the parameter other. For full credit, the resulting bag should
not include any duplicates. For example, if b1 represents the bag {2, 2, 3, 5, 7, 7, 7, 8} and b2
represents the bag {2, 3, 4, 5, 5, 6, 7}, then b1.unionWith(b2) should return an ListBag
representing the bag {2, 3, 4, 5, 6, 7, 8}. If there are no items in either bag, the method should
return an empty ListBag. As a result, your method should use method calls to access the internals
of that bag. See our implementation of the containsAll() method for an example of this.
---------------------------------------------------------------------------------------------------------------
# An implementation of a Bag Class using a list.
from random import randrange
class ListBag:
# Default, no-arg constructor - creates a new, empty ArrayBag with
# the default maximum size.
def __init__ (self):
self.items = None
self.numItems = 0
# add - adds the specified item to the Bag.
def add(self, item):
if item is None:
print("Added item is illegal")
else:
if self.items is None:
self.items = []
self.items.append(item)
self.numItems += 1
else:
self.items.append(item)
self.numItems = self.numItems + 1
# remove - removes one occurrence of the specified item (if any)
# from the Bag. Returns true on success and false if the
# specified item (i.e., an object equal to item) is not in the Bag.
def remove(self, item):
for i in range(self.numItems):
if self.items[i] == item:
self.items.remove(item)
self.numItems = self.numItems - 1
return True
return False # item not found
# contains - returns true if the specified item is in the ListBag, and
# false otherwise.
def contains(self, item):
return item in self.items
# containsAll - does this ListBag contain all of the items in
# otherBag? Returns false if otherBag is null or empty.
def containsAll(self, otherBag):
if otherBag is None or otherBag.numItems == 0:
return False
other = otherBag.toList()
for i in range(len(otherBag.items)):
if not self.contains(otherBag.items[i]):
return False
return True
# numOfItems - returns the number of items in the Bag.
def numOfItems(self):
return self.numItems
# grab - returns a reference to a randomly chosen in the Bag.
def grab(self):
if self.numItems == 0:
print("the bag is empty")
return None
whichOne = randrange(0, self.numItems)
return self.items[whichOne]
# toList - return an list containing the current contents of the bag
def toList(self):
copy = ListBag()
for i in range(self.numItems):
copy.add(self.items[i])
return copy
# __str__ - converts this ListBag into a readable string.
def __str__(self):
s = "{"
for i in range(self.numItems - 1):
s = s + " " + str(self.items[i]) + ","
s = s + " " + str(self.items[-1]) + " }"
return s
# isEmpty - add method description
def isEmpty(self):
pass
# remove the pass statement and add you solution
# numOccur - add method description
def numOccur(self, item):
pass
# remove the pass statement and add you solution
# addItems - add method description
def addItems(self, other):
pass
# remove the pass statement and add you solution
# equals - add method description
def equals(self, item):
pass
# remove the pass statement and add you solution
# unionWith - add method description
def unionWith(self, item):
pass
# remove the pass statement and add you solution
# Test the ListBag implementation.
# Create an ListBag named bag1.
bag1 = ListBag()
bag1.add(None)
# Determine size of bag1
size = eval(input("Size of bag 1: "))
for i in range(size):
bag1.add(i)
# Print bag1
print("bag 1 = " + str(bag1))
print()
# Print number of items in bag1
print("bag 1 has " + str(bag1.numOfItems()) + " items.")
# Select a random item and print it.
item = bag1.grab()
print("grabbed " + str(item))
print("bag 1 = " + str(bag1))
# Iterate over the objects in bag1, printing them one per line.
for i in bag1.items:
print(i)
print()
# Get an item to remove from bag1, remove it, and reprint the bag.
itemStr = int(input("item to remove: "))
if bag1.contains(itemStr):
bag1.remove(itemStr)
print("bag 1 = " + str(bag1))
print()
else:
print("item not in bag")
print()
# Make a copy of bag1 and call it bag2
print("bag 1 = " + str(bag1))
bag2 = bag1.toList()
print("bag 2 = " + str(bag2))
print()
# Check if bag2 contains all of the items in bag1
if bag2.containsAll(bag1):
print("bag 1 contains all elements in bag 2.")
print()
else:
print("bag 1 does not contain all elements in bag 2.")
print()
# Remove 6 from bag2
bag2.remove(6)
print("bag 1 = " + str(bag1))
print("bag 2 = " + str(bag2))
#Check if bag2 contains all of the items in bag1
if bag2.containsAll(bag1):
print("bag 1 contains all elements in bag 2.")
print()
else:
print("bag 1 does not contain all elements in bag 2.")
print()
# Check if bag1 contains all of the items bag2
if bag1.containsAll(bag2):
print("bag 2 contains all elements in bag 1.")
print()
else:
print("bag 2 does not contain all elements in bag 1.")
print()
# add testcase for the methods that you add, below
Solution
# An implementation of a Bag Class using a list.
from random import randrange
class ListBag:
# Default, no-arg constructor - creates a new, empty ArrayBag with
# the default maximum size.
def __init__ (self):
self.items = None
self.numItems = 0
# add - adds the specified item to the Bag.
def add(self, item):
if item is None:
print("Added item is illegal")
else:
if self.items is None:
self.items = []
self.items.append(item)
self.numItems += 1
else:
self.items.append(item)
self.numItems = self.numItems + 1
# remove - removes one occurrence of the specified item (if any)
# from the Bag. Returns true on success and false if the
# specified item (i.e., an object equal to item) is not in the Bag.
def remove(self, item):
for i in range(self.numItems):
if self.items[i] == item:
self.items.remove(item)
self.numItems = self.numItems - 1
return True
return False # item not found
# contains - returns true if the specified item is in the ListBag, and
# false otherwise.
def contains(self, item):
return item in self.items
# containsAll - does this ListBag contain all of the items in
# otherBag? Returns false if otherBag is null or empty.
def containsAll(self, otherBag):
if otherBag is None or otherBag.numItems == 0:
return False
other = otherBag.toList()
for i in range(len(otherBag.items)):
if not self.contains(otherBag.items[i]):
return False
return True
# numOfItems - returns the number of items in the Bag.
def numOfItems(self):
return self.numItems
# grab - returns a reference to a randomly chosen in the Bag.
def grab(self):
if self.numItems == 0:
print("the bag is empty")
return None
whichOne = randrange(0, self.numItems)
return self.items[whichOne]
# toList - return an list containing the current contents of the bag
def toList(self):
copy = ListBag()
for i in range(self.numItems):
copy.add(self.items[i])
return copy
# __str__ - converts this ListBag into a readable string.
def __str__(self):
s = "{"
for i in range(self.numItems - 1):
s = s + " " + str(self.items[i]) + ","
s = s + " " + str(self.items[-1]) + " }"
return s
# isEmpty - add method description
def isEmpty(self):
pass
# remove the pass statement and add you solution
# numOccur - add method description
def numOccur(self, item):
pass
# remove the pass statement and add you solution
# addItems - add method description
def addItems(self, other):
pass
# remove the pass statement and add you solution
# equals - add method description
def equals(self, item):
pass
# remove the pass statement and add you solution
# unionWith - add method description
def unionWith(self, item):
pass
# remove the pass statement and add you solution
# Test the ListBag implementation.
# Create an ListBag named bag1.
bag1 = ListBag()
bag1.add(None)
# Determine size of bag1
size = eval(input("Size of bag 1: "))
for i in range(size):
bag1.add(i)
# Print bag1
print("bag 1 = " + str(bag1))
print()
# Print number of items in bag1
print("bag 1 has " + str(bag1.numOfItems()) + " items.")
# Select a random item and print it.
item = bag1.grab()
print("grabbed " + str(item))
print("bag 1 = " + str(bag1))
# Iterate over the objects in bag1, printing them one per line.
for i in bag1.items:
print(i)
print()
# Get an item to remove from bag1, remove it, and reprint the bag.
itemStr = int(input("item to remove: "))
if bag1.contains(itemStr):
bag1.remove(itemStr)
print("bag 1 = " + str(bag1))
print()
else:
print("item not in bag")
print()
# Make a copy of bag1 and call it bag2
print("bag 1 = " + str(bag1))
bag2 = bag1.toList()
print("bag 2 = " + str(bag2))
print()
# Check if bag2 contains all of the items in bag1
if bag2.containsAll(bag1):
print("bag 1 contains all elements in bag 2.")
print()
else:
print("bag 1 does not contain all elements in bag 2.")
print()
# Remove 6 from bag2
bag2.remove(6)
print("bag 1 = " + str(bag1))
print("bag 2 = " + str(bag2))
#Check if bag2 contains all of the items in bag1
if bag2.containsAll(bag1):
print("bag 1 contains all elements in bag 2.")
print()
else:
print("bag 1 does not contain all elements in bag 2.")
print()
# Check if bag1 contains all of the items bag2
if bag1.containsAll(bag2):
print("bag 2 contains all elements in bag 1.")
print()
else:
print("bag 2 does not contain all elements in bag 1.")
print()
# add testcase for the methods that you add, below

More Related Content

Similar to Adding methods to the ListBag classIn the file ListBag.py, add the.pdf

Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdfAssignment4 Assignment 4 Hashtables In this assignment we w.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
kksrivastava1
 
I need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdfI need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdf
fantoosh1
 
Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docx
Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docxChapter 05.DS_StoreChapter 05arraybag.pyFile array.docx
Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docx
tidwellveronique
 
Due November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdfDue November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdf
abibagschennai
 
Lecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docxLecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docx
SHIVA101531
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
adinathassociates
 

Similar to Adding methods to the ListBag classIn the file ListBag.py, add the.pdf (20)

Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdfAssignment4 Assignment 4 Hashtables In this assignment we w.pdf
Assignment4 Assignment 4 Hashtables In this assignment we w.pdf
 
Chapt03
Chapt03Chapt03
Chapt03
 
I need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdfI need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdf
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
 
ECET 370 Redefined Education--ecet370.com
ECET 370 Redefined Education--ecet370.comECET 370 Redefined Education--ecet370.com
ECET 370 Redefined Education--ecet370.com
 
ECET 370 Education Planning--ecet370.com
 ECET 370 Education Planning--ecet370.com ECET 370 Education Planning--ecet370.com
ECET 370 Education Planning--ecet370.com
 
Collections
CollectionsCollections
Collections
 
ECET 370 Invent Yourself/newtonhelp.com
ECET 370 Invent Yourself/newtonhelp.comECET 370 Invent Yourself/newtonhelp.com
ECET 370 Invent Yourself/newtonhelp.com
 
ECET 370 Effective Communication/tutorialrank.com
 ECET 370 Effective Communication/tutorialrank.com ECET 370 Effective Communication/tutorialrank.com
ECET 370 Effective Communication/tutorialrank.com
 
Array list(1)
Array list(1)Array list(1)
Array list(1)
 
ECET 370 Achievement Education -- www.ecet370.com
ECET 370 Achievement Education -- www.ecet370.comECET 370 Achievement Education -- www.ecet370.com
ECET 370 Achievement Education -- www.ecet370.com
 
Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docx
Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docxChapter 05.DS_StoreChapter 05arraybag.pyFile array.docx
Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docx
 
Due November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdfDue November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdf
 
Collection Framework-1.pptx
Collection Framework-1.pptxCollection Framework-1.pptx
Collection Framework-1.pptx
 
ECET 370 Inspiring Innovation--ecet370.com
ECET 370 Inspiring Innovation--ecet370.comECET 370 Inspiring Innovation--ecet370.com
ECET 370 Inspiring Innovation--ecet370.com
 
Lecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docxLecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docx
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
Ecet 370 week 2 lab 2
Ecet 370 week 2 lab 2Ecet 370 week 2 lab 2
Ecet 370 week 2 lab 2
 

More from mohammedfootwear

Getting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdfGetting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdf
mohammedfootwear
 
Describe one safeguard that should be in place to protect the confid.pdf
Describe one safeguard that should be in place to protect the confid.pdfDescribe one safeguard that should be in place to protect the confid.pdf
Describe one safeguard that should be in place to protect the confid.pdf
mohammedfootwear
 
Create a storyboard prototype of a mobile app.When creating a stor.pdf
Create a storyboard prototype of a mobile app.When creating a stor.pdfCreate a storyboard prototype of a mobile app.When creating a stor.pdf
Create a storyboard prototype of a mobile app.When creating a stor.pdf
mohammedfootwear
 
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
mohammedfootwear
 
C programming. Answer question only in C code In the eighth part, yo.pdf
C programming. Answer question only in C code In the eighth part, yo.pdfC programming. Answer question only in C code In the eighth part, yo.pdf
C programming. Answer question only in C code In the eighth part, yo.pdf
mohammedfootwear
 
You will choose a country, other than the USA or Turkey, that you wo.pdf
You will choose a country, other than the USA or Turkey, that you wo.pdfYou will choose a country, other than the USA or Turkey, that you wo.pdf
You will choose a country, other than the USA or Turkey, that you wo.pdf
mohammedfootwear
 
What is the correct answer Chrome File Edit View History Bookmarks.pdf
What is the correct answer Chrome File Edit View History Bookmarks.pdfWhat is the correct answer Chrome File Edit View History Bookmarks.pdf
What is the correct answer Chrome File Edit View History Bookmarks.pdf
mohammedfootwear
 
Using SQL Developer ONLY!Your assignment is to create an auditing .pdf
Using SQL Developer ONLY!Your assignment is to create an auditing .pdfUsing SQL Developer ONLY!Your assignment is to create an auditing .pdf
Using SQL Developer ONLY!Your assignment is to create an auditing .pdf
mohammedfootwear
 
This for English class.I need help for writing 4 to 5 paragraphs a.pdf
This for English class.I need help for writing 4 to 5 paragraphs a.pdfThis for English class.I need help for writing 4 to 5 paragraphs a.pdf
This for English class.I need help for writing 4 to 5 paragraphs a.pdf
mohammedfootwear
 

More from mohammedfootwear (20)

Getting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdfGetting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdf
 
Discuss what is meant by Project Scope ManagementSolutionA pr.pdf
Discuss what is meant by Project Scope ManagementSolutionA pr.pdfDiscuss what is meant by Project Scope ManagementSolutionA pr.pdf
Discuss what is meant by Project Scope ManagementSolutionA pr.pdf
 
Determine if statement is true or false. If johnny likes suzy the ri.pdf
Determine if statement is true or false. If johnny likes suzy the ri.pdfDetermine if statement is true or false. If johnny likes suzy the ri.pdf
Determine if statement is true or false. If johnny likes suzy the ri.pdf
 
Describe one safeguard that should be in place to protect the confid.pdf
Describe one safeguard that should be in place to protect the confid.pdfDescribe one safeguard that should be in place to protect the confid.pdf
Describe one safeguard that should be in place to protect the confid.pdf
 
Create a storyboard prototype of a mobile app.When creating a stor.pdf
Create a storyboard prototype of a mobile app.When creating a stor.pdfCreate a storyboard prototype of a mobile app.When creating a stor.pdf
Create a storyboard prototype of a mobile app.When creating a stor.pdf
 
Are you familiar with the term parochialism What could be happen.pdf
Are you familiar with the term parochialism What could be happen.pdfAre you familiar with the term parochialism What could be happen.pdf
Are you familiar with the term parochialism What could be happen.pdf
 
Answer the question, What market structure is the airline industry.pdf
Answer the question, What market structure is the airline industry.pdfAnswer the question, What market structure is the airline industry.pdf
Answer the question, What market structure is the airline industry.pdf
 
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
 
C programming. Answer question only in C code In the eighth part, yo.pdf
C programming. Answer question only in C code In the eighth part, yo.pdfC programming. Answer question only in C code In the eighth part, yo.pdf
C programming. Answer question only in C code In the eighth part, yo.pdf
 
Biology Lab questions1. Why can a very small amount of bacteria b.pdf
Biology Lab questions1. Why can a very small amount of bacteria b.pdfBiology Lab questions1. Why can a very small amount of bacteria b.pdf
Biology Lab questions1. Why can a very small amount of bacteria b.pdf
 
You will choose a country, other than the USA or Turkey, that you wo.pdf
You will choose a country, other than the USA or Turkey, that you wo.pdfYou will choose a country, other than the USA or Turkey, that you wo.pdf
You will choose a country, other than the USA or Turkey, that you wo.pdf
 
Why does the RNA polymerase complex in eukaryotes contain a histone .pdf
Why does the RNA polymerase complex in eukaryotes contain a histone .pdfWhy does the RNA polymerase complex in eukaryotes contain a histone .pdf
Why does the RNA polymerase complex in eukaryotes contain a histone .pdf
 
what Linux command allows you to scan the disk for partition changes.pdf
what Linux command allows you to scan the disk for partition changes.pdfwhat Linux command allows you to scan the disk for partition changes.pdf
what Linux command allows you to scan the disk for partition changes.pdf
 
What is the correct answer Chrome File Edit View History Bookmarks.pdf
What is the correct answer Chrome File Edit View History Bookmarks.pdfWhat is the correct answer Chrome File Edit View History Bookmarks.pdf
What is the correct answer Chrome File Edit View History Bookmarks.pdf
 
What is fault tolerance, and what network aspects must be monitored .pdf
What is fault tolerance, and what network aspects must be monitored .pdfWhat is fault tolerance, and what network aspects must be monitored .pdf
What is fault tolerance, and what network aspects must be monitored .pdf
 
Using SQL Developer ONLY!Your assignment is to create an auditing .pdf
Using SQL Developer ONLY!Your assignment is to create an auditing .pdfUsing SQL Developer ONLY!Your assignment is to create an auditing .pdf
Using SQL Developer ONLY!Your assignment is to create an auditing .pdf
 
Use the definition of big- Theta to prove that 5x^4 + 2x^3 - 1 is The.pdf
Use the definition of big- Theta to prove that 5x^4 + 2x^3 - 1 is The.pdfUse the definition of big- Theta to prove that 5x^4 + 2x^3 - 1 is The.pdf
Use the definition of big- Theta to prove that 5x^4 + 2x^3 - 1 is The.pdf
 
To what degree, if any, has America’s ascendancy on the world stage .pdf
To what degree, if any, has America’s ascendancy on the world stage .pdfTo what degree, if any, has America’s ascendancy on the world stage .pdf
To what degree, if any, has America’s ascendancy on the world stage .pdf
 
This for English class.I need help for writing 4 to 5 paragraphs a.pdf
This for English class.I need help for writing 4 to 5 paragraphs a.pdfThis for English class.I need help for writing 4 to 5 paragraphs a.pdf
This for English class.I need help for writing 4 to 5 paragraphs a.pdf
 
The debt ratio is the relationship between O A. total assets and cur.pdf
The debt ratio is the relationship between O A. total assets and cur.pdfThe debt ratio is the relationship between O A. total assets and cur.pdf
The debt ratio is the relationship between O A. total assets and cur.pdf
 

Recently uploaded

會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 

Recently uploaded (20)

會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptx
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
Scopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsScopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS Publications
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 

Adding methods to the ListBag classIn the file ListBag.py, add the.pdf

  • 1. Adding methods to the ListBag class In the file ListBag.py, add the methods described below to the ListBag class, and then add code to test these methods. You should not add any new instance variables (fields) to the class. def isEmpty(self) This method should return True if the ListBag is empty, and False otherwise. def numOccur(self, item) This method should return the number of times that the parameter item occurs in the called ListBag. For example, if b1 represents the bag {7, 5, 3, 5, 7, 2, 7}, then b1.numOccur(2) should return 1, b1.numOccur(7) should return 3, and b1.numOccur(20) should return 0. def addItems(self, other) This method should attempt to add to the called ListBag all of the items found in the parameter other. As a result, your method should use method calls to access the internals of that bag. See our implementation of the containsAll() method for an example of this. def equals(self, other) This method should determine if the called ListBag is equal to the parameter other. Two bags are equal if they contain the same items. The location of the items in the bags does not matter (e.g., {5, 6, 6, 7} is equal to {7, 6, 5, 6}), but bags that are equal must have the same number of occurrences of each item (e.g., {5, 6, 6, 7} is not equal to {5, 6, 7}). The method should return True if the two bags are equal, and False otherwise (including cases in which the parameter is None). Your method should use method calls to access the internals of that bag. See our implementation of the containsAll() method for an example of this. You are strongly encouraged you to have yourequalsmethod take advantage of one of the other methods that you are implementing for this problem. def unionWith(self, other) This method should create and return an ListBag containing one occurrence of any item that is found in either the called object or the parameter other. For full credit, the resulting bag should not include any duplicates. For example, if b1 represents the bag {2, 2, 3, 5, 7, 7, 7, 8} and b2 represents the bag {2, 3, 4, 5, 5, 6, 7}, then b1.unionWith(b2) should return an ListBag representing the bag {2, 3, 4, 5, 6, 7, 8}. If there are no items in either bag, the method should return an empty ListBag. As a result, your method should use method calls to access the internals of that bag. See our implementation of the containsAll() method for an example of this. --------------------------------------------------------------------------------------------------------------- # An implementation of a Bag Class using a list. from random import randrange
  • 2. class ListBag: # Default, no-arg constructor - creates a new, empty ArrayBag with # the default maximum size. def __init__ (self): self.items = None self.numItems = 0 # add - adds the specified item to the Bag. def add(self, item): if item is None: print("Added item is illegal") else: if self.items is None: self.items = [] self.items.append(item) self.numItems += 1 else: self.items.append(item) self.numItems = self.numItems + 1 # remove - removes one occurrence of the specified item (if any) # from the Bag. Returns true on success and false if the # specified item (i.e., an object equal to item) is not in the Bag. def remove(self, item): for i in range(self.numItems): if self.items[i] == item: self.items.remove(item) self.numItems = self.numItems - 1 return True return False # item not found # contains - returns true if the specified item is in the ListBag, and # false otherwise. def contains(self, item): return item in self.items
  • 3. # containsAll - does this ListBag contain all of the items in # otherBag? Returns false if otherBag is null or empty. def containsAll(self, otherBag): if otherBag is None or otherBag.numItems == 0: return False other = otherBag.toList() for i in range(len(otherBag.items)): if not self.contains(otherBag.items[i]): return False return True # numOfItems - returns the number of items in the Bag. def numOfItems(self): return self.numItems # grab - returns a reference to a randomly chosen in the Bag. def grab(self): if self.numItems == 0: print("the bag is empty") return None whichOne = randrange(0, self.numItems) return self.items[whichOne] # toList - return an list containing the current contents of the bag def toList(self): copy = ListBag() for i in range(self.numItems): copy.add(self.items[i]) return copy # __str__ - converts this ListBag into a readable string. def __str__(self): s = "{" for i in range(self.numItems - 1): s = s + " " + str(self.items[i]) + "," s = s + " " + str(self.items[-1]) + " }" return s
  • 4. # isEmpty - add method description def isEmpty(self): pass # remove the pass statement and add you solution # numOccur - add method description def numOccur(self, item): pass # remove the pass statement and add you solution # addItems - add method description def addItems(self, other): pass # remove the pass statement and add you solution # equals - add method description def equals(self, item): pass # remove the pass statement and add you solution # unionWith - add method description def unionWith(self, item): pass # remove the pass statement and add you solution # Test the ListBag implementation. # Create an ListBag named bag1. bag1 = ListBag() bag1.add(None) # Determine size of bag1 size = eval(input("Size of bag 1: ")) for i in range(size): bag1.add(i) # Print bag1 print("bag 1 = " + str(bag1)) print() # Print number of items in bag1 print("bag 1 has " + str(bag1.numOfItems()) + " items.")
  • 5. # Select a random item and print it. item = bag1.grab() print("grabbed " + str(item)) print("bag 1 = " + str(bag1)) # Iterate over the objects in bag1, printing them one per line. for i in bag1.items: print(i) print() # Get an item to remove from bag1, remove it, and reprint the bag. itemStr = int(input("item to remove: ")) if bag1.contains(itemStr): bag1.remove(itemStr) print("bag 1 = " + str(bag1)) print() else: print("item not in bag") print() # Make a copy of bag1 and call it bag2 print("bag 1 = " + str(bag1)) bag2 = bag1.toList() print("bag 2 = " + str(bag2)) print() # Check if bag2 contains all of the items in bag1 if bag2.containsAll(bag1): print("bag 1 contains all elements in bag 2.") print() else: print("bag 1 does not contain all elements in bag 2.") print() # Remove 6 from bag2 bag2.remove(6) print("bag 1 = " + str(bag1)) print("bag 2 = " + str(bag2)) #Check if bag2 contains all of the items in bag1 if bag2.containsAll(bag1):
  • 6. print("bag 1 contains all elements in bag 2.") print() else: print("bag 1 does not contain all elements in bag 2.") print() # Check if bag1 contains all of the items bag2 if bag1.containsAll(bag2): print("bag 2 contains all elements in bag 1.") print() else: print("bag 2 does not contain all elements in bag 1.") print() # add testcase for the methods that you add, below Solution # An implementation of a Bag Class using a list. from random import randrange class ListBag: # Default, no-arg constructor - creates a new, empty ArrayBag with # the default maximum size. def __init__ (self): self.items = None self.numItems = 0 # add - adds the specified item to the Bag. def add(self, item): if item is None: print("Added item is illegal") else: if self.items is None: self.items = [] self.items.append(item)
  • 7. self.numItems += 1 else: self.items.append(item) self.numItems = self.numItems + 1 # remove - removes one occurrence of the specified item (if any) # from the Bag. Returns true on success and false if the # specified item (i.e., an object equal to item) is not in the Bag. def remove(self, item): for i in range(self.numItems): if self.items[i] == item: self.items.remove(item) self.numItems = self.numItems - 1 return True return False # item not found # contains - returns true if the specified item is in the ListBag, and # false otherwise. def contains(self, item): return item in self.items # containsAll - does this ListBag contain all of the items in # otherBag? Returns false if otherBag is null or empty. def containsAll(self, otherBag): if otherBag is None or otherBag.numItems == 0: return False other = otherBag.toList() for i in range(len(otherBag.items)): if not self.contains(otherBag.items[i]): return False return True # numOfItems - returns the number of items in the Bag. def numOfItems(self): return self.numItems # grab - returns a reference to a randomly chosen in the Bag. def grab(self):
  • 8. if self.numItems == 0: print("the bag is empty") return None whichOne = randrange(0, self.numItems) return self.items[whichOne] # toList - return an list containing the current contents of the bag def toList(self): copy = ListBag() for i in range(self.numItems): copy.add(self.items[i]) return copy # __str__ - converts this ListBag into a readable string. def __str__(self): s = "{" for i in range(self.numItems - 1): s = s + " " + str(self.items[i]) + "," s = s + " " + str(self.items[-1]) + " }" return s # isEmpty - add method description def isEmpty(self): pass # remove the pass statement and add you solution # numOccur - add method description def numOccur(self, item): pass # remove the pass statement and add you solution # addItems - add method description def addItems(self, other): pass # remove the pass statement and add you solution # equals - add method description def equals(self, item): pass # remove the pass statement and add you solution
  • 9. # unionWith - add method description def unionWith(self, item): pass # remove the pass statement and add you solution # Test the ListBag implementation. # Create an ListBag named bag1. bag1 = ListBag() bag1.add(None) # Determine size of bag1 size = eval(input("Size of bag 1: ")) for i in range(size): bag1.add(i) # Print bag1 print("bag 1 = " + str(bag1)) print() # Print number of items in bag1 print("bag 1 has " + str(bag1.numOfItems()) + " items.") # Select a random item and print it. item = bag1.grab() print("grabbed " + str(item)) print("bag 1 = " + str(bag1)) # Iterate over the objects in bag1, printing them one per line. for i in bag1.items: print(i) print() # Get an item to remove from bag1, remove it, and reprint the bag. itemStr = int(input("item to remove: ")) if bag1.contains(itemStr): bag1.remove(itemStr) print("bag 1 = " + str(bag1)) print() else:
  • 10. print("item not in bag") print() # Make a copy of bag1 and call it bag2 print("bag 1 = " + str(bag1)) bag2 = bag1.toList() print("bag 2 = " + str(bag2)) print() # Check if bag2 contains all of the items in bag1 if bag2.containsAll(bag1): print("bag 1 contains all elements in bag 2.") print() else: print("bag 1 does not contain all elements in bag 2.") print() # Remove 6 from bag2 bag2.remove(6) print("bag 1 = " + str(bag1)) print("bag 2 = " + str(bag2)) #Check if bag2 contains all of the items in bag1 if bag2.containsAll(bag1): print("bag 1 contains all elements in bag 2.") print() else: print("bag 1 does not contain all elements in bag 2.") print() # Check if bag1 contains all of the items bag2 if bag1.containsAll(bag2): print("bag 2 contains all elements in bag 1.") print() else: print("bag 2 does not contain all elements in bag 1.") print() # add testcase for the methods that you add, below