SlideShare a Scribd company logo
1 of 7
Download to read offline
Please help me get this Mind - tap homework to validate
Programming Exercise 5.7
Complete the implementation of the link-based set defined in the new class named LinkedSet
that implements a set type using linked nodes.
Hint: Much of the code in the LinkedBag class from your solution of the linkedbag.py file in
Programming Exercise 5.5 can be reused.
In the linkedset.py file, complete the following:
Complete the accessor methods:
isEmpty(), returns true if len(self) == 0, or false otherwise.
__len__, returns the number of items in self.
__str__, returns the string representation of self.
__iter__, supports iteration over a view of self.
__add__, returns anew set containing the contents of self and other
clone, return a copy of self.
__eq__, returns true if self equals other, or false otherwise
count, return the numer of instance of item in self.
Complete the mutator methods:
clear, makes self become empty.
add, adds item to self and ignores the item if its already in the set.
Check array memory and increase it if necessary
remove, removes item from self if it's in self.
Check precondition and raise KeyError if necessary
Search for the node containing the target item, probe will point to the target node, and trailer will
point to the one before it, if it exists.
Unhook the node to be deleted, either the first one or one thereafter.
Decrement logical size
To test your program run the test method in the testset.py file.
Your program's output should look like the following:
Grading
Write your Python code in the code editor. Use the Run button to execute and run the code. To
review your progress, open up the "Tasks" panel on the left to view the curated list of tasks for
the project.
Once you are happy with the test results, click Submit and then the Confirm button to submit
your project for grading.
+++.Linkedbag.py+++
Reuse your solution from Programming Exercise 5.5 as your starter file
"""
from node import Node
from abstractbag import AbstractBag
class LinkedBag(AbstractBag):
def __init__(self,sourceCollection = None):
self._items = None
AbstractBag.__init__(self, sourceCollection)
def __iter__(self):
cursor = self._items
while not cursor is None:
yield cursor.data
cursor = cursor.next
def add(self, item):
self._items = Node(item, self._items)
self._size += 1
def append(self, item):
node = Node(item, None)
if self.isEmpty():
self._items = node
else:
cursor = self._items
while cursor.next != None:
cursor = cursor.next
cursor.next = node
self._size +=1
+++Linkedset.py+++
from node import Node
import copy
class LinkedSet(object):
"""A link-based set implementation."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self, which includes the
contents of sourceCollection, if it's present."""
#add the items in the LinkedSet
self.head = None
self.temp = self.head
self.count = 0
for num in sourceCollection[::-1]:
#check if the first element is None
if self.head is None:
self.temp = Node(num)
self.head = self.temp
else:
self.temp.next = Node(num)
self.temp = self.temp.next
self.count += 1
# Accessor methods
def isEmpty(self):
"""Returns True if len(self) == 0, or False otherwise."""
#check if the head is None or not
if self.head:
return False
else:
return True
def __len__(self):
"""-Returns the number of items in self."""
#return the count
return self.count
def __str__(self):
"""Returns the string representation of self."""
ans = "Expect the set's string : {"
self.temp = self.head
while self.temp.next != None:
ans += str(self.temp.data)+ ","
self.temp = self.temp.next
ans += str(self.temp.data)+"}"
return ans
def __iter__(self):
"""Supports iteration over a view of self."""
self.temp = self.head
while self.temp is not None:
yield self.temp
self.temp = self.temp.next
def __add__(self, other):
"""Returns a new set containing the contents
of self and other."""
ans = set()
self.temp = self.head
while self.temp is not None:
ans.add(self.temp.data)
self.temp = self.temp.next
#for each element in the other linked list check if it is present in self
#if not the add it
other.temp = other.head
while other.temp is not None:
ans.add(other.temp.data)
other.temp = other.temp.next
return ans
def clone(self):
"""Returns a copy of self."""
temp = copy.copy(self.head )
return temp
def __eq__(self, other):
"""Returns True if self equals other,
or False otherwise."""
other.temp = other.head
self.temp = self.head
while self.temp.data and other.temp.data :
if self.temp.data != other.temp.data :
return False
other.temp = other.temp.next
self.temp = self.temp.next
if self.temp is None and other.temp is None:
return True
return False
# Mutator methods
def clear(self):
"""Makes self become empty."""
self.head = None
def add(self, item):
"""Adds item to self."""
self.temp = self.head
#check if item is present in the linked list
while(self.temp.next != None):
if self.temp.data == item:
return
self.temp = self.temp.next
if self.temp.data != item:
self.temp.next = Node(item)
self.count += 1
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item in not in self.
Postcondition: item is removed from self."""
self.temp = self.head
while(self.temp.next.data != item):
self.temp = self.temp.next
self.temp.next = self.temp.next.next
self.count -= 1
++++testset.py+++++
from linkedset import LinkedSet
def test(setType):
"""Expects a bag type as an argument and runs some tests
on objects of that type."""
print("Testing", setType)
lyst = list(range(1, 11))
print("The list of items added is:", lyst)
s = setType(lyst)
print("Expect the set's string:", s)
print("Add same items to test for uniqueness:")
for i in range(1, 11):
s.add(i)
print("Expect the set's string:", s)
test(LinkedSet)
++++Node.py++++
class Node(object):
"""Represents a singly linked node."""
def __init__(self, data, next = None):
self.data = data
self.next = next

More Related Content

Similar to Please help me get this Mind - tap homework to validateProgramming.pdf

Assignment 6 as a reference public class ArrExample pr.pdf
Assignment 6 as a reference   public class ArrExample    pr.pdfAssignment 6 as a reference   public class ArrExample    pr.pdf
Assignment 6 as a reference public class ArrExample pr.pdf
kksrivastava1
 
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
info706022
 
The Final Programming Project
The Final Programming ProjectThe Final Programming Project
The Final Programming Project
Sage Jacobs
 
OverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docxOverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docx
alfred4lewis58146
 
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdfAdding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
mohammedfootwear
 
3.4 Summary This chapter included the system of the device and c.docx
3.4 Summary This chapter included the system of the device and c.docx3.4 Summary This chapter included the system of the device and c.docx
3.4 Summary This chapter included the system of the device and c.docx
rhetttrevannion
 
0_ML lab programs updated123 (3).1687933796093.doc
0_ML lab programs updated123 (3).1687933796093.doc0_ML lab programs updated123 (3).1687933796093.doc
0_ML lab programs updated123 (3).1687933796093.doc
RohanS38
 
There are a couple of new methods that you will be writing for this pr.pdf
There are a couple of new methods that you will be writing for this pr.pdfThere are a couple of new methods that you will be writing for this pr.pdf
There are a couple of new methods that you will be writing for this pr.pdf
aamousnowov
 

Similar to Please help me get this Mind - tap homework to validateProgramming.pdf (20)

Assignment 6 as a reference public class ArrExample pr.pdf
Assignment 6 as a reference   public class ArrExample    pr.pdfAssignment 6 as a reference   public class ArrExample    pr.pdf
Assignment 6 as a reference public class ArrExample pr.pdf
 
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
 
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
 
ECET 370 HELPS Education Counseling--ecet370helps.com
ECET 370 HELPS  Education Counseling--ecet370helps.comECET 370 HELPS  Education Counseling--ecet370helps.com
ECET 370 HELPS Education Counseling--ecet370helps.com
 
ECET 370 HELPS Redefined Education--ecet370helps.com
ECET 370 HELPS Redefined Education--ecet370helps.comECET 370 HELPS Redefined Education--ecet370helps.com
ECET 370 HELPS Redefined Education--ecet370helps.com
 
The Final Programming Project
The Final Programming ProjectThe Final Programming Project
The Final Programming Project
 
ECET 370 Success Begins/Newtonhelp.com
ECET 370 Success Begins/Newtonhelp.comECET 370 Success Begins/Newtonhelp.com
ECET 370 Success Begins/Newtonhelp.com
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
OverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docxOverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docx
 
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdfAdding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
 
[Python] [Singly-linked list] [Element insertion] Consider the follo.pdf
[Python] [Singly-linked list] [Element insertion] Consider the follo.pdf[Python] [Singly-linked list] [Element insertion] Consider the follo.pdf
[Python] [Singly-linked list] [Element insertion] Consider the follo.pdf
 
3.4 Summary This chapter included the system of the device and c.docx
3.4 Summary This chapter included the system of the device and c.docx3.4 Summary This chapter included the system of the device and c.docx
3.4 Summary This chapter included the system of the device and c.docx
 
0_ML lab programs updated123 (3).1687933796093.doc
0_ML lab programs updated123 (3).1687933796093.doc0_ML lab programs updated123 (3).1687933796093.doc
0_ML lab programs updated123 (3).1687933796093.doc
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
There are a couple of new methods that you will be writing for this pr.pdf
There are a couple of new methods that you will be writing for this pr.pdfThere are a couple of new methods that you will be writing for this pr.pdf
There are a couple of new methods that you will be writing for this pr.pdf
 
Collections
CollectionsCollections
Collections
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
 

More from amarrex323

Please help make class diagram. below is final tableFinal Table.pdf
Please help make class diagram. below is final tableFinal Table.pdfPlease help make class diagram. below is final tableFinal Table.pdf
Please help make class diagram. below is final tableFinal Table.pdf
amarrex323
 
please help me on the case! provide step by step explainations!.pdf
please help me on the case! provide step by step explainations!.pdfplease help me on the case! provide step by step explainations!.pdf
please help me on the case! provide step by step explainations!.pdf
amarrex323
 
Please look at the customer-introduced variable and service designed.pdf
Please look at the customer-introduced variable and service designed.pdfPlease look at the customer-introduced variable and service designed.pdf
Please look at the customer-introduced variable and service designed.pdf
amarrex323
 
Please I want an exact and correct answerQuality Management Modu.pdf
Please I want an exact and correct answerQuality Management Modu.pdfPlease I want an exact and correct answerQuality Management Modu.pdf
Please I want an exact and correct answerQuality Management Modu.pdf
amarrex323
 
Please help with this question.Please help with this question. O.pdf
Please help with this question.Please help with this question. O.pdfPlease help with this question.Please help with this question. O.pdf
Please help with this question.Please help with this question. O.pdf
amarrex323
 
please help implement the following in C. below are instructions and.pdf
please help implement the following in C. below are instructions and.pdfplease help implement the following in C. below are instructions and.pdf
please help implement the following in C. below are instructions and.pdf
amarrex323
 
please help and include explanations for a better understanding than.pdf
please help and include explanations for a better understanding than.pdfplease help and include explanations for a better understanding than.pdf
please help and include explanations for a better understanding than.pdf
amarrex323
 

More from amarrex323 (20)

Please help me with the linux commands for the following tasks. I am.pdf
Please help me with the linux commands for the following tasks. I am.pdfPlease help me with the linux commands for the following tasks. I am.pdf
Please help me with the linux commands for the following tasks. I am.pdf
 
Please help make class diagram. below is final tableFinal Table.pdf
Please help make class diagram. below is final tableFinal Table.pdfPlease help make class diagram. below is final tableFinal Table.pdf
Please help make class diagram. below is final tableFinal Table.pdf
 
please help me on the case! provide step by step explainations!.pdf
please help me on the case! provide step by step explainations!.pdfplease help me on the case! provide step by step explainations!.pdf
please help me on the case! provide step by step explainations!.pdf
 
Please provide class diagram. 2) The admin module will allow car .pdf
Please provide class diagram. 2) The admin module will allow car .pdfPlease provide class diagram. 2) The admin module will allow car .pdf
Please provide class diagram. 2) The admin module will allow car .pdf
 
Please Prove using pumping lemma 2. Show that the language Lnp={w{a,.pdf
Please Prove using pumping lemma 2. Show that the language Lnp={w{a,.pdfPlease Prove using pumping lemma 2. Show that the language Lnp={w{a,.pdf
Please Prove using pumping lemma 2. Show that the language Lnp={w{a,.pdf
 
Please help me to solve this one! (a) Let X1,X2,�,Xn,Xn+1,�,X2n be.pdf
Please help me to solve this one! (a) Let X1,X2,�,Xn,Xn+1,�,X2n be.pdfPlease help me to solve this one! (a) Let X1,X2,�,Xn,Xn+1,�,X2n be.pdf
Please help me to solve this one! (a) Let X1,X2,�,Xn,Xn+1,�,X2n be.pdf
 
Please make the program runs at O(nlogm) see arrayfun. h for doc.pdf
Please make the program runs at O(nlogm)  see arrayfun. h for doc.pdfPlease make the program runs at O(nlogm)  see arrayfun. h for doc.pdf
Please make the program runs at O(nlogm) see arrayfun. h for doc.pdf
 
Please help me to critique this articleAgency Theory Perspect.pdf
Please help me to critique this articleAgency Theory Perspect.pdfPlease help me to critique this articleAgency Theory Perspect.pdf
Please help me to critique this articleAgency Theory Perspect.pdf
 
please match each of these terms with the best description each o.pdf
please match each of these terms with the best description  each o.pdfplease match each of these terms with the best description  each o.pdf
please match each of these terms with the best description each o.pdf
 
Please look at the customer-introduced variable and service designed.pdf
Please look at the customer-introduced variable and service designed.pdfPlease look at the customer-introduced variable and service designed.pdf
Please look at the customer-introduced variable and service designed.pdf
 
Please I want an exact and correct answerQuality Management Modu.pdf
Please I want an exact and correct answerQuality Management Modu.pdfPlease I want an exact and correct answerQuality Management Modu.pdf
Please I want an exact and correct answerQuality Management Modu.pdf
 
please i need help to write paper and which should be 5-8 pages i.pdf
please i need help to write paper  and which should be 5-8 pages i.pdfplease i need help to write paper  and which should be 5-8 pages i.pdf
please i need help to write paper and which should be 5-8 pages i.pdf
 
please helpWrite the vhdl code of a delay flip flop with the .pdf
please helpWrite the vhdl code of  a delay flip flop with the .pdfplease helpWrite the vhdl code of  a delay flip flop with the .pdf
please helpWrite the vhdl code of a delay flip flop with the .pdf
 
Please Help!5.list of all sentences along with criminals informati.pdf
Please Help!5.list of all sentences along with criminals informati.pdfPlease Help!5.list of all sentences along with criminals informati.pdf
Please Help!5.list of all sentences along with criminals informati.pdf
 
please help asap!!! Alternation of generationsThe paragraph below.pdf
please help asap!!! Alternation of generationsThe paragraph below.pdfplease help asap!!! Alternation of generationsThe paragraph below.pdf
please help asap!!! Alternation of generationsThe paragraph below.pdf
 
Please help with this question.Please help with this question. O.pdf
Please help with this question.Please help with this question. O.pdfPlease help with this question.Please help with this question. O.pdf
Please help with this question.Please help with this question. O.pdf
 
please help implement the following in C. below are instructions and.pdf
please help implement the following in C. below are instructions and.pdfplease help implement the following in C. below are instructions and.pdf
please help implement the following in C. below are instructions and.pdf
 
Please help me with this. Thank you. .pdf
Please help me with this. Thank you.                            .pdfPlease help me with this. Thank you.                            .pdf
Please help me with this. Thank you. .pdf
 
Please help with ALL parts of the question. I will upvote if correct.pdf
Please help with ALL parts of the question. I will upvote if correct.pdfPlease help with ALL parts of the question. I will upvote if correct.pdf
Please help with ALL parts of the question. I will upvote if correct.pdf
 
please help and include explanations for a better understanding than.pdf
please help and include explanations for a better understanding than.pdfplease help and include explanations for a better understanding than.pdf
please help and include explanations for a better understanding than.pdf
 

Recently uploaded

Recently uploaded (20)

Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 

Please help me get this Mind - tap homework to validateProgramming.pdf

  • 1. Please help me get this Mind - tap homework to validate Programming Exercise 5.7 Complete the implementation of the link-based set defined in the new class named LinkedSet that implements a set type using linked nodes. Hint: Much of the code in the LinkedBag class from your solution of the linkedbag.py file in Programming Exercise 5.5 can be reused. In the linkedset.py file, complete the following: Complete the accessor methods: isEmpty(), returns true if len(self) == 0, or false otherwise. __len__, returns the number of items in self. __str__, returns the string representation of self. __iter__, supports iteration over a view of self. __add__, returns anew set containing the contents of self and other clone, return a copy of self. __eq__, returns true if self equals other, or false otherwise count, return the numer of instance of item in self. Complete the mutator methods: clear, makes self become empty. add, adds item to self and ignores the item if its already in the set. Check array memory and increase it if necessary remove, removes item from self if it's in self. Check precondition and raise KeyError if necessary Search for the node containing the target item, probe will point to the target node, and trailer will point to the one before it, if it exists. Unhook the node to be deleted, either the first one or one thereafter. Decrement logical size To test your program run the test method in the testset.py file. Your program's output should look like the following: Grading Write your Python code in the code editor. Use the Run button to execute and run the code. To review your progress, open up the "Tasks" panel on the left to view the curated list of tasks for the project. Once you are happy with the test results, click Submit and then the Confirm button to submit your project for grading.
  • 2. +++.Linkedbag.py+++ Reuse your solution from Programming Exercise 5.5 as your starter file """ from node import Node from abstractbag import AbstractBag class LinkedBag(AbstractBag): def __init__(self,sourceCollection = None): self._items = None AbstractBag.__init__(self, sourceCollection) def __iter__(self): cursor = self._items while not cursor is None: yield cursor.data cursor = cursor.next def add(self, item): self._items = Node(item, self._items) self._size += 1 def append(self, item): node = Node(item, None) if self.isEmpty(): self._items = node else: cursor = self._items while cursor.next != None: cursor = cursor.next cursor.next = node self._size +=1 +++Linkedset.py+++ from node import Node
  • 3. import copy class LinkedSet(object): """A link-based set implementation.""" # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" #add the items in the LinkedSet self.head = None self.temp = self.head self.count = 0 for num in sourceCollection[::-1]: #check if the first element is None if self.head is None: self.temp = Node(num) self.head = self.temp else: self.temp.next = Node(num) self.temp = self.temp.next self.count += 1 # Accessor methods def isEmpty(self): """Returns True if len(self) == 0, or False otherwise.""" #check if the head is None or not if self.head: return False else: return True def __len__(self): """-Returns the number of items in self.""" #return the count
  • 4. return self.count def __str__(self): """Returns the string representation of self.""" ans = "Expect the set's string : {" self.temp = self.head while self.temp.next != None: ans += str(self.temp.data)+ "," self.temp = self.temp.next ans += str(self.temp.data)+"}" return ans def __iter__(self): """Supports iteration over a view of self.""" self.temp = self.head while self.temp is not None: yield self.temp self.temp = self.temp.next def __add__(self, other): """Returns a new set containing the contents of self and other.""" ans = set() self.temp = self.head while self.temp is not None: ans.add(self.temp.data) self.temp = self.temp.next #for each element in the other linked list check if it is present in self #if not the add it other.temp = other.head while other.temp is not None:
  • 5. ans.add(other.temp.data) other.temp = other.temp.next return ans def clone(self): """Returns a copy of self.""" temp = copy.copy(self.head ) return temp def __eq__(self, other): """Returns True if self equals other, or False otherwise.""" other.temp = other.head self.temp = self.head while self.temp.data and other.temp.data : if self.temp.data != other.temp.data : return False other.temp = other.temp.next self.temp = self.temp.next if self.temp is None and other.temp is None: return True return False # Mutator methods def clear(self): """Makes self become empty.""" self.head = None def add(self, item):
  • 6. """Adds item to self.""" self.temp = self.head #check if item is present in the linked list while(self.temp.next != None): if self.temp.data == item: return self.temp = self.temp.next if self.temp.data != item: self.temp.next = Node(item) self.count += 1 def remove(self, item): """Precondition: item is in self. Raises: KeyError if item in not in self. Postcondition: item is removed from self.""" self.temp = self.head while(self.temp.next.data != item): self.temp = self.temp.next self.temp.next = self.temp.next.next self.count -= 1 ++++testset.py+++++ from linkedset import LinkedSet def test(setType): """Expects a bag type as an argument and runs some tests on objects of that type.""" print("Testing", setType) lyst = list(range(1, 11)) print("The list of items added is:", lyst) s = setType(lyst) print("Expect the set's string:", s)
  • 7. print("Add same items to test for uniqueness:") for i in range(1, 11): s.add(i) print("Expect the set's string:", s) test(LinkedSet) ++++Node.py++++ class Node(object): """Represents a singly linked node.""" def __init__(self, data, next = None): self.data = data self.next = next