SlideShare a Scribd company logo
1 of 4
Mod 4 Homeork Enhanced DoublyLinkedList
Starter Code:
# Do not modify this class
class Node:
'Node object to be used in DoublyLinkedList'
def __init__(self, item, _next=None, _prev=None):
'initializes new node objects'
self.item = item
self._next = _next
self._prev = _prev
def __repr__(self):
'String representation of Node'
return f"Node({self.item})"
class DoublyLinkedList:
def __init__(self, items=None):
'Construct a new DLL object'
self._head = None
self._tail = None
self._len = 0
self._nodes = dict() # dictionary of item:node pairs
# initialize list w/ items if specified
if items is not None:
for item in items:
self.add_last(item)
def __len__(self):
'returns number of nodes in DLL'
return self._len
# TODO: Modify the 4 methods below to keep `self._nodes` up-to-date
def add_first(self, item):
'adds item to front of dll'
# add new node as head
self._head = Node(item, _next=self._head, _prev=None)
self._len += 1
# if that was the first node
if len(self) == 1: self._tail = self._head
# otherwise, redirect old heads ._tail pointer
else: self._head._next._prev = self._head
def add_last(self, item):
'adds item to end of dll'
# add new node as head
self._tail = Node(item, _next=None, _prev=self._tail)
self._len += 1
# if that was the first node
if len(self) == 1: self._head = self._tail
# otherwise, redirect old heads ._tail pointer
else: self._tail._prev._next = self._tail
def remove_first(self):
'removes and returns first item'
if len(self) == 0: raise RuntimeError("cannot remove from empty dll")
# extract item for later
item = self._head.item
# move up head pointer
self._head = self._head._next
self._len -= 1
# was that the last node?
if len(self) == 0: self._tail = None
else: self._head._prev = None
return item
def remove_last(self):
'removes and returns last item'
if len(self) == 0: raise RuntimeError("cannot remove from empty dll")
# extract item for later
item = self._tail.item
# move up tail pointer
self._tail = self._tail._prev
self._len -= 1
# was that the last node?
if len(self) == 0: self._head = None
else: self._tail._next = None
return item
# TODO: Add a docstring and implement
def __contains__(self, item):
raise NotImplementedError
# TODO: Add a docstring and implement
def neighbors(self, item):
raise NotImplementedError
# TODO: Add a docstring and implement
def remove_node(self, item):
raise NotImplementedError
Mod 4 Homework - Enhanced DoublyLinkedList Doubly Linked Lists (DLLs) support O ( 1 )
addition and removal from either end, making them a great choice for queues or deques. A
downside of DLLs (and other linked data structures) is that it takes linear time ( O ( n )) to access
nodes in the middle - in a traditional DLL, we have to start at the beginning and continually call
node._next until we get to the node we're looking for. Here, we'll enhance a DLL with a
dictionary of item:node pairs to give us O ( 1 ) access to interior nodes. This will speed up
membership testing, node insertion at arbitrary locations, and removal of arbitrary nodes to O ( 1
) . This is a common design pattern we'll see with other linked data structures like heaps and
graphs. Some downsides of this approach to keep in mind: - Dictionary keys must be unique, so
this will only work if node items are unique. - Storing and maintaining the dictionary will not
asymptotically worsen our O ( 1 ) running times or O ( n ) memory usage, but it will negatively
impact both. Figure 1: (a) In a standard DLL, we can only access the head and tail nodes in O ( 1
) . (b) By using a dictionary of item:node pairs, we can immediately jump to any node, as long as
we know which item we are interested in. 1) Add a dictionary DoublyLinkedList.py provides
basic Node and DoublyLinkedList classes that supports typical DLL operations. Modify these
methods to keep the nodes dictionary up to date with item:node pairs as you add and remove
from the DLL so you can access any node in O ( 1 ) . 2) Implement ___ contains__(item) _nodes
is a private attribute, and thus should not be called explicilty in your tests. Instead, use _nodes to
> dll = DoublyLinkedList (range (5)) 3 in dll # O ( 1 ) , even though 3 is in the middle True 5 in
dll # Note the use of 'in' to call the dunder method __contains__() False Write a unittest that
verifies contains works as expected as you add and remove nodes. 3) Implement neighbors
(item) Add a method neighbors (item) to your DoublyLinkedList class that returns the items
immediately before and after the node with item: dll = DoublyLinkedList(range (5)) dll
.neighbors(3) ( 2 , 4 ) dll .neighbors(0) # Edge case - head (None, 1) dll.neighbors(4) # Edge
case - tail (3, None) Add a method neighbors (item) to your DoublyLinkedList class that returns
the items immediately before and after the node with item: > d l 1 = DoublyLinkedList(range
(5)) > d ll .neighbors(3) ( 2 , 4 ) > d ll .neighbors(0) # Edge case - head (None, 1)
dll.neighbors(4) # Edge case - tail (3, None) - Should be O ( 1 ) - When called on the item stored
in the head/tail, return None as the previous/next item, as shown above - Raise a RuntimeError if
someone searches for an item not in the DLL Include unittests for the above behavior (except the
running time). 4) Implement remove_node (item) Add a method that removes the node
containing an item from your DLL. - O ( 1 ) - Make sure to "stitch together" the adjacent nodes -
Edge cases you should be able to handle: - Raise a RuntimeError if someone tries to remove an
item not in the DLL - Removing the head - Removing the tail Include unittests for the above
behavior (except the running time).

More Related Content

Similar to Mod 4 Homeork Enhanced DoublyLinkedList Starter Code- # Do not modify.docx

[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.pdfisenbergwarne4100
 
How to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footHow to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footSofia Fateeva
 
How to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footHow to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footPVS-Studio
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Basic R Learning
Basic R LearningBasic R Learning
Basic R LearningKumar P
 
The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31Mahmoud Samir Fayed
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptxjack881
 
singly link list project in dsa.....by rohit malav
singly link list project in dsa.....by rohit malavsingly link list project in dsa.....by rohit malav
singly link list project in dsa.....by rohit malavRohit malav
 
The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptxVijaykota11
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 

Similar to Mod 4 Homeork Enhanced DoublyLinkedList Starter Code- # Do not modify.docx (20)

[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
 
How to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footHow to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the foot
 
How to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footHow to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the foot
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
advancedR.pdf
advancedR.pdfadvancedR.pdf
advancedR.pdf
 
Advanced r
Advanced rAdvanced r
Advanced r
 
Basic R Learning
Basic R LearningBasic R Learning
Basic R Learning
 
Advanced R cheat sheet
Advanced R cheat sheetAdvanced R cheat sheet
Advanced R cheat sheet
 
The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 
singly link list project in dsa.....by rohit malav
singly link list project in dsa.....by rohit malavsingly link list project in dsa.....by rohit malav
singly link list project in dsa.....by rohit malav
 
The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
linked.ppt
linked.pptlinked.ppt
linked.ppt
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 

More from Jason0x0Scottw

A company's stock price rose 3-4- in 2011 - and in 2012 - it increased.docx
A company's stock price rose 3-4- in 2011 - and in 2012 - it increased.docxA company's stock price rose 3-4- in 2011 - and in 2012 - it increased.docx
A company's stock price rose 3-4- in 2011 - and in 2012 - it increased.docxJason0x0Scottw
 
A company has the following- Dec- 1 Beginning inventory 15 units at $6.docx
A company has the following- Dec- 1 Beginning inventory 15 units at $6.docxA company has the following- Dec- 1 Beginning inventory 15 units at $6.docx
A company has the following- Dec- 1 Beginning inventory 15 units at $6.docxJason0x0Scottw
 
A company must perform a maintenance project consisting of seven activ.docx
A company must perform a maintenance project consisting of seven activ.docxA company must perform a maintenance project consisting of seven activ.docx
A company must perform a maintenance project consisting of seven activ.docxJason0x0Scottw
 
A company has paid out all its current and accumulated earnings a prof.docx
A company has paid out all its current and accumulated earnings a prof.docxA company has paid out all its current and accumulated earnings a prof.docx
A company has paid out all its current and accumulated earnings a prof.docxJason0x0Scottw
 
New Public Management- clearly provide the following- (1) establish th.docx
New Public Management- clearly provide the following- (1) establish th.docxNew Public Management- clearly provide the following- (1) establish th.docx
New Public Management- clearly provide the following- (1) establish th.docxJason0x0Scottw
 
New Corporation- a C corporation- had the following items for the curr.docx
New Corporation- a C corporation- had the following items for the curr.docxNew Corporation- a C corporation- had the following items for the curr.docx
New Corporation- a C corporation- had the following items for the curr.docxJason0x0Scottw
 
networking networking Which of the following Topologies are available.docx
networking networking Which of the following Topologies are available.docxnetworking networking Which of the following Topologies are available.docx
networking networking Which of the following Topologies are available.docxJason0x0Scottw
 
Neighborhood Effects 1- What is the neighborhood effect- 2- How to ide.docx
Neighborhood Effects 1- What is the neighborhood effect- 2- How to ide.docxNeighborhood Effects 1- What is the neighborhood effect- 2- How to ide.docx
Neighborhood Effects 1- What is the neighborhood effect- 2- How to ide.docxJason0x0Scottw
 
need help with filling out the results table!! ( provided pictures of.docx
need help with filling out the results table!!  ( provided pictures of.docxneed help with filling out the results table!!  ( provided pictures of.docx
need help with filling out the results table!! ( provided pictures of.docxJason0x0Scottw
 
need help with both please Methanogens are a group of archaea that ge.docx
need help with both please  Methanogens are a group of archaea that ge.docxneed help with both please  Methanogens are a group of archaea that ge.docx
need help with both please Methanogens are a group of archaea that ge.docxJason0x0Scottw
 
Need help finishing this doubly linked list code- Commented lines are.docx
Need help finishing this doubly linked list code- Commented lines are.docxNeed help finishing this doubly linked list code- Commented lines are.docx
Need help finishing this doubly linked list code- Commented lines are.docxJason0x0Scottw
 
Need help getting past an error in C++! I have all my code pasted down.docx
Need help getting past an error in C++! I have all my code pasted down.docxNeed help getting past an error in C++! I have all my code pasted down.docx
Need help getting past an error in C++! I have all my code pasted down.docxJason0x0Scottw
 
Narrow visible light emission Below left is a familiar visible-light v.docx
Narrow visible light emission Below left is a familiar visible-light v.docxNarrow visible light emission Below left is a familiar visible-light v.docx
Narrow visible light emission Below left is a familiar visible-light v.docxJason0x0Scottw
 
Name the three major hormones produced by thyroid tissues and give spe.docx
Name the three major hormones produced by thyroid tissues and give spe.docxName the three major hormones produced by thyroid tissues and give spe.docx
Name the three major hormones produced by thyroid tissues and give spe.docxJason0x0Scottw
 
Name the type and tunics of blood vessels and the major tissue typers).docx
Name the type and tunics of blood vessels and the major tissue typers).docxName the type and tunics of blood vessels and the major tissue typers).docx
Name the type and tunics of blood vessels and the major tissue typers).docxJason0x0Scottw
 
name it Provide the names of Bone A and Bone D.docx
name it Provide the names of Bone A and Bone D.docxname it Provide the names of Bone A and Bone D.docx
name it Provide the names of Bone A and Bone D.docxJason0x0Scottw
 
name it Provide the name of Letter A - Letter B and Letter C Be sure t.docx
name it Provide the name of Letter A - Letter B and Letter C Be sure t.docxname it Provide the name of Letter A - Letter B and Letter C Be sure t.docx
name it Provide the name of Letter A - Letter B and Letter C Be sure t.docxJason0x0Scottw
 
Name and define each component of the preparedness cycle- What is a HV.docx
Name and define each component of the preparedness cycle- What is a HV.docxName and define each component of the preparedness cycle- What is a HV.docx
Name and define each component of the preparedness cycle- What is a HV.docxJason0x0Scottw
 
Myopia (nearsightedness) Rays focus in front of retina Concave lens co.docx
Myopia (nearsightedness) Rays focus in front of retina Concave lens co.docxMyopia (nearsightedness) Rays focus in front of retina Concave lens co.docx
Myopia (nearsightedness) Rays focus in front of retina Concave lens co.docxJason0x0Scottw
 

More from Jason0x0Scottw (20)

A company's stock price rose 3-4- in 2011 - and in 2012 - it increased.docx
A company's stock price rose 3-4- in 2011 - and in 2012 - it increased.docxA company's stock price rose 3-4- in 2011 - and in 2012 - it increased.docx
A company's stock price rose 3-4- in 2011 - and in 2012 - it increased.docx
 
A company has the following- Dec- 1 Beginning inventory 15 units at $6.docx
A company has the following- Dec- 1 Beginning inventory 15 units at $6.docxA company has the following- Dec- 1 Beginning inventory 15 units at $6.docx
A company has the following- Dec- 1 Beginning inventory 15 units at $6.docx
 
A company must perform a maintenance project consisting of seven activ.docx
A company must perform a maintenance project consisting of seven activ.docxA company must perform a maintenance project consisting of seven activ.docx
A company must perform a maintenance project consisting of seven activ.docx
 
A company has paid out all its current and accumulated earnings a prof.docx
A company has paid out all its current and accumulated earnings a prof.docxA company has paid out all its current and accumulated earnings a prof.docx
A company has paid out all its current and accumulated earnings a prof.docx
 
New Public Management- clearly provide the following- (1) establish th.docx
New Public Management- clearly provide the following- (1) establish th.docxNew Public Management- clearly provide the following- (1) establish th.docx
New Public Management- clearly provide the following- (1) establish th.docx
 
New Corporation- a C corporation- had the following items for the curr.docx
New Corporation- a C corporation- had the following items for the curr.docxNew Corporation- a C corporation- had the following items for the curr.docx
New Corporation- a C corporation- had the following items for the curr.docx
 
networking networking Which of the following Topologies are available.docx
networking networking Which of the following Topologies are available.docxnetworking networking Which of the following Topologies are available.docx
networking networking Which of the following Topologies are available.docx
 
Neighborhood Effects 1- What is the neighborhood effect- 2- How to ide.docx
Neighborhood Effects 1- What is the neighborhood effect- 2- How to ide.docxNeighborhood Effects 1- What is the neighborhood effect- 2- How to ide.docx
Neighborhood Effects 1- What is the neighborhood effect- 2- How to ide.docx
 
need help with filling out the results table!! ( provided pictures of.docx
need help with filling out the results table!!  ( provided pictures of.docxneed help with filling out the results table!!  ( provided pictures of.docx
need help with filling out the results table!! ( provided pictures of.docx
 
need help with both please Methanogens are a group of archaea that ge.docx
need help with both please  Methanogens are a group of archaea that ge.docxneed help with both please  Methanogens are a group of archaea that ge.docx
need help with both please Methanogens are a group of archaea that ge.docx
 
Need help finishing this doubly linked list code- Commented lines are.docx
Need help finishing this doubly linked list code- Commented lines are.docxNeed help finishing this doubly linked list code- Commented lines are.docx
Need help finishing this doubly linked list code- Commented lines are.docx
 
Need help getting past an error in C++! I have all my code pasted down.docx
Need help getting past an error in C++! I have all my code pasted down.docxNeed help getting past an error in C++! I have all my code pasted down.docx
Need help getting past an error in C++! I have all my code pasted down.docx
 
Narrow visible light emission Below left is a familiar visible-light v.docx
Narrow visible light emission Below left is a familiar visible-light v.docxNarrow visible light emission Below left is a familiar visible-light v.docx
Narrow visible light emission Below left is a familiar visible-light v.docx
 
Name the three major hormones produced by thyroid tissues and give spe.docx
Name the three major hormones produced by thyroid tissues and give spe.docxName the three major hormones produced by thyroid tissues and give spe.docx
Name the three major hormones produced by thyroid tissues and give spe.docx
 
Name the type and tunics of blood vessels and the major tissue typers).docx
Name the type and tunics of blood vessels and the major tissue typers).docxName the type and tunics of blood vessels and the major tissue typers).docx
Name the type and tunics of blood vessels and the major tissue typers).docx
 
name it Provide the names of Bone A and Bone D.docx
name it Provide the names of Bone A and Bone D.docxname it Provide the names of Bone A and Bone D.docx
name it Provide the names of Bone A and Bone D.docx
 
name it Provide the name of Letter A - Letter B and Letter C Be sure t.docx
name it Provide the name of Letter A - Letter B and Letter C Be sure t.docxname it Provide the name of Letter A - Letter B and Letter C Be sure t.docx
name it Provide the name of Letter A - Letter B and Letter C Be sure t.docx
 
Name and define each component of the preparedness cycle- What is a HV.docx
Name and define each component of the preparedness cycle- What is a HV.docxName and define each component of the preparedness cycle- What is a HV.docx
Name and define each component of the preparedness cycle- What is a HV.docx
 
n-.docx
n-.docxn-.docx
n-.docx
 
Myopia (nearsightedness) Rays focus in front of retina Concave lens co.docx
Myopia (nearsightedness) Rays focus in front of retina Concave lens co.docxMyopia (nearsightedness) Rays focus in front of retina Concave lens co.docx
Myopia (nearsightedness) Rays focus in front of retina Concave lens co.docx
 

Recently uploaded

Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxCeline George
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxneillewis46
 
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 ManagementMBA Assignment Experts
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjMohammed Sikander
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
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 17Celine George
 
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 Partnershipsexpandedwebsite
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxMarlene Maheu
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxMichaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxRugvedSathawane
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Celine George
 
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfRich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfJerry Chew
 
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...EduSkills OECD
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 

Recently uploaded (20)

Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
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
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
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
 
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
 
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"
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxMichaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfRich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
 
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...
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 

Mod 4 Homeork Enhanced DoublyLinkedList Starter Code- # Do not modify.docx

  • 1. Mod 4 Homeork Enhanced DoublyLinkedList Starter Code: # Do not modify this class class Node: 'Node object to be used in DoublyLinkedList' def __init__(self, item, _next=None, _prev=None): 'initializes new node objects' self.item = item self._next = _next self._prev = _prev def __repr__(self): 'String representation of Node' return f"Node({self.item})" class DoublyLinkedList: def __init__(self, items=None): 'Construct a new DLL object' self._head = None self._tail = None self._len = 0 self._nodes = dict() # dictionary of item:node pairs # initialize list w/ items if specified if items is not None: for item in items: self.add_last(item) def __len__(self): 'returns number of nodes in DLL' return self._len # TODO: Modify the 4 methods below to keep `self._nodes` up-to-date def add_first(self, item): 'adds item to front of dll' # add new node as head self._head = Node(item, _next=self._head, _prev=None) self._len += 1 # if that was the first node if len(self) == 1: self._tail = self._head
  • 2. # otherwise, redirect old heads ._tail pointer else: self._head._next._prev = self._head def add_last(self, item): 'adds item to end of dll' # add new node as head self._tail = Node(item, _next=None, _prev=self._tail) self._len += 1 # if that was the first node if len(self) == 1: self._head = self._tail # otherwise, redirect old heads ._tail pointer else: self._tail._prev._next = self._tail def remove_first(self): 'removes and returns first item' if len(self) == 0: raise RuntimeError("cannot remove from empty dll") # extract item for later item = self._head.item # move up head pointer self._head = self._head._next self._len -= 1 # was that the last node? if len(self) == 0: self._tail = None else: self._head._prev = None return item def remove_last(self): 'removes and returns last item' if len(self) == 0: raise RuntimeError("cannot remove from empty dll") # extract item for later item = self._tail.item # move up tail pointer self._tail = self._tail._prev self._len -= 1 # was that the last node? if len(self) == 0: self._head = None
  • 3. else: self._tail._next = None return item # TODO: Add a docstring and implement def __contains__(self, item): raise NotImplementedError # TODO: Add a docstring and implement def neighbors(self, item): raise NotImplementedError # TODO: Add a docstring and implement def remove_node(self, item): raise NotImplementedError Mod 4 Homework - Enhanced DoublyLinkedList Doubly Linked Lists (DLLs) support O ( 1 ) addition and removal from either end, making them a great choice for queues or deques. A downside of DLLs (and other linked data structures) is that it takes linear time ( O ( n )) to access nodes in the middle - in a traditional DLL, we have to start at the beginning and continually call node._next until we get to the node we're looking for. Here, we'll enhance a DLL with a dictionary of item:node pairs to give us O ( 1 ) access to interior nodes. This will speed up membership testing, node insertion at arbitrary locations, and removal of arbitrary nodes to O ( 1 ) . This is a common design pattern we'll see with other linked data structures like heaps and graphs. Some downsides of this approach to keep in mind: - Dictionary keys must be unique, so this will only work if node items are unique. - Storing and maintaining the dictionary will not asymptotically worsen our O ( 1 ) running times or O ( n ) memory usage, but it will negatively impact both. Figure 1: (a) In a standard DLL, we can only access the head and tail nodes in O ( 1 ) . (b) By using a dictionary of item:node pairs, we can immediately jump to any node, as long as we know which item we are interested in. 1) Add a dictionary DoublyLinkedList.py provides basic Node and DoublyLinkedList classes that supports typical DLL operations. Modify these methods to keep the nodes dictionary up to date with item:node pairs as you add and remove from the DLL so you can access any node in O ( 1 ) . 2) Implement ___ contains__(item) _nodes is a private attribute, and thus should not be called explicilty in your tests. Instead, use _nodes to > dll = DoublyLinkedList (range (5)) 3 in dll # O ( 1 ) , even though 3 is in the middle True 5 in dll # Note the use of 'in' to call the dunder method __contains__() False Write a unittest that verifies contains works as expected as you add and remove nodes. 3) Implement neighbors (item) Add a method neighbors (item) to your DoublyLinkedList class that returns the items immediately before and after the node with item: dll = DoublyLinkedList(range (5)) dll .neighbors(3) ( 2 , 4 ) dll .neighbors(0) # Edge case - head (None, 1) dll.neighbors(4) # Edge case - tail (3, None) Add a method neighbors (item) to your DoublyLinkedList class that returns the items immediately before and after the node with item: > d l 1 = DoublyLinkedList(range (5)) > d ll .neighbors(3) ( 2 , 4 ) > d ll .neighbors(0) # Edge case - head (None, 1) dll.neighbors(4) # Edge case - tail (3, None) - Should be O ( 1 ) - When called on the item stored in the head/tail, return None as the previous/next item, as shown above - Raise a RuntimeError if someone searches for an item not in the DLL Include unittests for the above behavior (except the
  • 4. running time). 4) Implement remove_node (item) Add a method that removes the node containing an item from your DLL. - O ( 1 ) - Make sure to "stitch together" the adjacent nodes - Edge cases you should be able to handle: - Raise a RuntimeError if someone tries to remove an item not in the DLL - Removing the head - Removing the tail Include unittests for the above behavior (except the running time).