SlideShare a Scribd company logo
1 of 7
Download to read offline
DATA STRUCTURES IN PYTHON DLL
PLEASE DO NOT COPY AND PASTE FROM PREVIOUS CHEGG ANSWERS I'VE
CHECKED THEM ALL THEY'RE WRONG
DO NOT USE ANY OTHER DATA STRUCTURE THAN DLL (MEANING NO LISTS,
DICTIONARIES)
PLEASE ADD THE FUNCTIONS TO THE CODE AND MAKE SURE IT RUNS
#CODE
class DLL:
class _Node:
def __init__(self, data, next=None, prev=None):
self._data = data
self._next = next
self._prev = prev
def __str__(self):
return '({0})'.format(self._data)
def __init__(self):
self._h = None
self._t = None
self._size = 0
def __str__(self):
st = "List=<"
curr = self._h
while curr is not None:
st = st + str(curr._data)
# st = st + str(curr)
if curr._next is not None:
st = st + ","
curr = curr._next
return st+">"
def __contains__(self, val):
curr = self._h
while curr is not None:
if curr._data == val:
return True
curr = curr._next
return False
def isEmpty(self):
return self._h is None
def headNode(self):
return self._h
def tailNode(self):
return self._t
def head_val(self):
if not self.isEmpty():
return self._h._data
else:
raise TypeError("None value")
def tail_val(self):
if not self.isEmpty():
return self._t._data
else:
raise TypeError("None value")
def printF(self):
p = self._h
while p is not None:
print(p._data, end=",")
p = p._next
print()
def printR(self):
p = self._t
while p is not None:
print(p._data, end=",")
p = p._prev
print()
def addToHead(self, data):
newNode = self._Node(data, self._h, None)
if self._h is not None:
self._h._prev = newNode
self._h = newNode
if self._t is None:
self._t = self._h
self._size += 1
def addToTail(self, data):
newNode = self._Node(data, None, self._t)
if self._t is not None:
self._t._next = newNode
self._t = newNode
if self._h is None:
self._h = newNode
self._size += 1
def removeHead(self):
if self.isEmpty():
raise TypeError("Empty")
if self._h == self._t: # one Node
self._h = self._t = None
else:
self._h = self._h._next
self._h._prev = None
self._size -= 1
def removeTail(self):
if self.isEmpty():
raise TypeError("Empty")
if self._h == self._t: # one Node
self._h = self._t = None
else:
self._t = self._t._prev
self._t._next = None
self._size -= 1
def clear(self):
self._h = self._t = None
self._size = 0
def remove(self, val):
if self.isEmpty():
return False
if self._h._data == val:
self.removeHead()
return True
# if self._h == self._t: # one Node
# return False
curr = self._h #._next
while curr._next is not None:
if curr._data == val:
curr._prev._next = curr._next
curr._next._prev = curr._prev
self._size -= 1
return True
curr = curr._next
if self._t._data == val:
self.removeTail()
return True
return False
def __len__(self):
return self._size
def __setitem__(self, k, val):
if k < 0:
raise IndexError("Index error < 0")
if k >= self._size:
raise IndexError("Index error > len")
curr = self._h
c = 0
while curr is not None:
if c == k:
curr._data = val
return
else:
c += 1
curr = curr._next
def __getitem__(self, k):
if k < 0:
raise IndexError("Index error < 0")
if k >= self._size:
raise IndexError("Index error > len")
curr = self._h
c = 0
while curr is not None:
if c == k:
return curr._data
else:
c += 1
curr = curr._next
def __delitem__(self, k):
if k < 0:
# raise IndexError("Index error < 0")
print("Index error")
return
if self.isEmpty():
return
if k == 0:
self.removeHead()
return
if k == self._size-1:
self.removeTail()
return
if k >= self._size:
# raise IndexError("Index > len")
print("Index error")
return
curr = self._h
c = 0
while curr._next is not None:
if c == k:
curr._prev._next = curr._next
curr._next._prev = curr._prev
self._size -= 1
return
else:
c += 1
curr = curr._next
# This function should be used in sorted list only
def insert(self, data):
if self.isEmpty() or data <= self._h._data:
self.addToHead(data)
return
if data >= self._t._data:
self.addToTail(data)
return
curr = self._h._next
while curr is not None:
if data <= curr._data:
newnode = self._Node(data, curr, curr._prev)
curr._prev._next = newnode
curr._prev = newnode
self._size += 1
return
else:
curr = curr._next
def extend(self, other):
curr = other._h
while curr is not None:
self.addToTail(curr._data)
curr = curr._next
def copy(self): # shallow copy
other = DLL()
# e is the result of self[];
# i.e. the result of getitem function
# for e in self:
# other.addToTail(e)
curr = self._h
while curr is not None:
other.addToTail(curr._data)
curr = curr._next
return other Ex1. Append Reverse (20 points) - Write the implementation of a member-
function appendReverse(self), which appends the current list in reverse order to the end of the
current list. This should be done in O(n). - Example: Assume that the current list =1,2,1,4,1,5 0
The function should change the current list to =1,2,1,4,1,5,5,1,4,1,2,1 Ex2. Accumulative Count
(20 points) - Write the most efficient implementation of the member-function acumCount(self),
which prints how long this current element exists in the remaining elements after the current
element. - Example: Assume that the current list =<1,2,1,4,1,4,2,5,2; then the output is
1:2<1,2,1,4,1,4,2,5,2>2:21,2,1,4,1,4,2,5,21:14:11:04:02:15:02:0

More Related Content

Similar to DATA STRUCTURES IN PYTHON DLLPLEASE DO NOT COPY AND PASTE FROM PRE.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
rhetttrevannion
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
# Imports# Include your imports here, if any are used. import.pdf
 # Imports# Include your imports here, if any are used. import.pdf # Imports# Include your imports here, if any are used. import.pdf
# Imports# Include your imports here, if any are used. import.pdf
gulshan16175gs
 
Will upvote asapPlease help my code gives me incorrect val.pdf
Will upvote asapPlease help my code gives me incorrect val.pdfWill upvote asapPlease help my code gives me incorrect val.pdf
Will upvote asapPlease help my code gives me incorrect val.pdf
sales223546
 
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
ANJALIENTERPRISES1
 
Please help me get this Mind - tap homework to validateProgramming.pdf
Please help me get this Mind - tap homework to validateProgramming.pdfPlease help me get this Mind - tap homework to validateProgramming.pdf
Please help me get this Mind - tap homework to validateProgramming.pdf
amarrex323
 
12th-computer-science-practical-study-material-english-medium.pdf
12th-computer-science-practical-study-material-english-medium.pdf12th-computer-science-practical-study-material-english-medium.pdf
12th-computer-science-practical-study-material-english-medium.pdf
ansh552818
 

Similar to DATA STRUCTURES IN PYTHON DLLPLEASE DO NOT COPY AND PASTE FROM PRE.pdf (20)

Odoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new apiOdoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new api
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Coding pilkades
Coding pilkadesCoding pilkades
Coding pilkades
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
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
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
# Imports# Include your imports here, if any are used. import.pdf
 # Imports# Include your imports here, if any are used. import.pdf # Imports# Include your imports here, if any are used. import.pdf
# Imports# Include your imports here, if any are used. import.pdf
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
 
Py Die R E A D M E
Py Die  R E A D M EPy Die  R E A D M E
Py Die R E A D M E
 
Will upvote asapPlease help my code gives me incorrect val.pdf
Will upvote asapPlease help my code gives me incorrect val.pdfWill upvote asapPlease help my code gives me incorrect val.pdf
Will upvote asapPlease help my code gives me incorrect val.pdf
 
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
 
Please help me get this Mind - tap homework to validateProgramming.pdf
Please help me get this Mind - tap homework to validateProgramming.pdfPlease help me get this Mind - tap homework to validateProgramming.pdf
Please help me get this Mind - tap homework to validateProgramming.pdf
 
python codes
python codespython codes
python codes
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Baby Steps to Machine Learning at DevFest Lagos 2019
Baby Steps to Machine Learning at DevFest Lagos 2019Baby Steps to Machine Learning at DevFest Lagos 2019
Baby Steps to Machine Learning at DevFest Lagos 2019
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
 
12th-computer-science-practical-study-material-english-medium.pdf
12th-computer-science-practical-study-material-english-medium.pdf12th-computer-science-practical-study-material-english-medium.pdf
12th-computer-science-practical-study-material-english-medium.pdf
 

More from Aggarwalelectronic18

Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdfCuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Aggarwalelectronic18
 
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdfCuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Aggarwalelectronic18
 

More from Aggarwalelectronic18 (20)

Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdfDemonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
Demonstrate cultural awareness of the Aboriginal andor Torres Strai.pdf
 
Deposit insuranceGroup of answer choicesleads depositors to be .pdf
Deposit insuranceGroup of answer choicesleads depositors to be .pdfDeposit insuranceGroup of answer choicesleads depositors to be .pdf
Deposit insuranceGroup of answer choicesleads depositors to be .pdf
 
Define the role of digital and social media in advertising and IBP a.pdf
Define the role of digital and social media in advertising and IBP a.pdfDefine the role of digital and social media in advertising and IBP a.pdf
Define the role of digital and social media in advertising and IBP a.pdf
 
Deep Learning for Vision Systems Given the following neural network .pdf
Deep Learning for Vision Systems Given the following neural network .pdfDeep Learning for Vision Systems Given the following neural network .pdf
Deep Learning for Vision Systems Given the following neural network .pdf
 
Debra Company began operations on June 1. The following transactions.pdf
Debra Company began operations on June 1. The following transactions.pdfDebra Company began operations on June 1. The following transactions.pdf
Debra Company began operations on June 1. The following transactions.pdf
 
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdfDe Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
De Yahoo!Finance, identifique la versi�n beta de las acciones de cua.pdf
 
Danone North America, un fabricante de productos l�cteos y de origen.pdf
Danone North America, un fabricante de productos l�cteos y de origen.pdfDanone North America, un fabricante de productos l�cteos y de origen.pdf
Danone North America, un fabricante de productos l�cteos y de origen.pdf
 
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdfCurtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
Curtis y Norma est�n casados y presentan una declaraci�n conjunta. C.pdf
 
Cultura y comercio el panorama internacional a las 900 horas; co.pdf
Cultura y comercio el panorama internacional a las 900 horas; co.pdfCultura y comercio el panorama internacional a las 900 horas; co.pdf
Cultura y comercio el panorama internacional a las 900 horas; co.pdf
 
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdfCurso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
Curso --- Comportamiento Organizacional (OBR250) Lea �Aceptand.pdf
 
Cultural Tourism ProductsThe environmental bubble is essentially a.pdf
Cultural Tourism ProductsThe environmental bubble is essentially a.pdfCultural Tourism ProductsThe environmental bubble is essentially a.pdf
Cultural Tourism ProductsThe environmental bubble is essentially a.pdf
 
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdfCuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
Cuando se trata de servicios sociales como salud, educaci�n y bienes.pdf
 
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdfCuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
Cuando se introdujo el euro en 1999, Grecia brillaba por su ausencia.pdf
 
Create your own Wikipedia pageWikipedia is one of the backbones of.pdf
Create your own Wikipedia pageWikipedia is one of the backbones of.pdfCreate your own Wikipedia pageWikipedia is one of the backbones of.pdf
Create your own Wikipedia pageWikipedia is one of the backbones of.pdf
 
Create the tables for your final project database using Design View.pdf
Create the tables for your final project database using Design View.pdfCreate the tables for your final project database using Design View.pdf
Create the tables for your final project database using Design View.pdf
 
Create a timeline that visually details the implementation steps of .pdf
Create a timeline that visually details the implementation steps of .pdfCreate a timeline that visually details the implementation steps of .pdf
Create a timeline that visually details the implementation steps of .pdf
 
Create a UML deployment and component diagram for the scenario below.pdf
Create a UML deployment and component diagram for the scenario below.pdfCreate a UML deployment and component diagram for the scenario below.pdf
Create a UML deployment and component diagram for the scenario below.pdf
 
Create a resume for yourself 1. 1-2 Pages 2. Any of the foll.pdf
Create a resume for yourself  1. 1-2 Pages  2. Any of the foll.pdfCreate a resume for yourself  1. 1-2 Pages  2. Any of the foll.pdf
Create a resume for yourself 1. 1-2 Pages 2. Any of the foll.pdf
 
Create a GUI application in Java that allows users to chat with each.pdf
Create a GUI application in Java that allows users to chat with each.pdfCreate a GUI application in Java that allows users to chat with each.pdf
Create a GUI application in Java that allows users to chat with each.pdf
 
create a cross section for X-Y create a cross section based on.pdf
create a cross section for X-Y create a cross section based on.pdfcreate a cross section for X-Y create a cross section based on.pdf
create a cross section for X-Y create a cross section based on.pdf
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

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)
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
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
 
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
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

DATA STRUCTURES IN PYTHON DLLPLEASE DO NOT COPY AND PASTE FROM PRE.pdf

  • 1. DATA STRUCTURES IN PYTHON DLL PLEASE DO NOT COPY AND PASTE FROM PREVIOUS CHEGG ANSWERS I'VE CHECKED THEM ALL THEY'RE WRONG DO NOT USE ANY OTHER DATA STRUCTURE THAN DLL (MEANING NO LISTS, DICTIONARIES) PLEASE ADD THE FUNCTIONS TO THE CODE AND MAKE SURE IT RUNS #CODE class DLL: class _Node: def __init__(self, data, next=None, prev=None): self._data = data self._next = next self._prev = prev def __str__(self): return '({0})'.format(self._data) def __init__(self): self._h = None self._t = None self._size = 0 def __str__(self): st = "List=<" curr = self._h while curr is not None: st = st + str(curr._data) # st = st + str(curr) if curr._next is not None: st = st + "," curr = curr._next return st+">" def __contains__(self, val): curr = self._h while curr is not None: if curr._data == val:
  • 2. return True curr = curr._next return False def isEmpty(self): return self._h is None def headNode(self): return self._h def tailNode(self): return self._t def head_val(self): if not self.isEmpty(): return self._h._data else: raise TypeError("None value") def tail_val(self): if not self.isEmpty(): return self._t._data else: raise TypeError("None value") def printF(self): p = self._h while p is not None: print(p._data, end=",") p = p._next print() def printR(self): p = self._t while p is not None: print(p._data, end=",") p = p._prev print() def addToHead(self, data): newNode = self._Node(data, self._h, None) if self._h is not None: self._h._prev = newNode self._h = newNode
  • 3. if self._t is None: self._t = self._h self._size += 1 def addToTail(self, data): newNode = self._Node(data, None, self._t) if self._t is not None: self._t._next = newNode self._t = newNode if self._h is None: self._h = newNode self._size += 1 def removeHead(self): if self.isEmpty(): raise TypeError("Empty") if self._h == self._t: # one Node self._h = self._t = None else: self._h = self._h._next self._h._prev = None self._size -= 1 def removeTail(self): if self.isEmpty(): raise TypeError("Empty") if self._h == self._t: # one Node self._h = self._t = None else: self._t = self._t._prev self._t._next = None self._size -= 1 def clear(self): self._h = self._t = None self._size = 0 def remove(self, val): if self.isEmpty(): return False if self._h._data == val:
  • 4. self.removeHead() return True # if self._h == self._t: # one Node # return False curr = self._h #._next while curr._next is not None: if curr._data == val: curr._prev._next = curr._next curr._next._prev = curr._prev self._size -= 1 return True curr = curr._next if self._t._data == val: self.removeTail() return True return False def __len__(self): return self._size def __setitem__(self, k, val): if k < 0: raise IndexError("Index error < 0") if k >= self._size: raise IndexError("Index error > len") curr = self._h c = 0 while curr is not None: if c == k: curr._data = val return else: c += 1 curr = curr._next def __getitem__(self, k): if k < 0: raise IndexError("Index error < 0") if k >= self._size:
  • 5. raise IndexError("Index error > len") curr = self._h c = 0 while curr is not None: if c == k: return curr._data else: c += 1 curr = curr._next def __delitem__(self, k): if k < 0: # raise IndexError("Index error < 0") print("Index error") return if self.isEmpty(): return if k == 0: self.removeHead() return if k == self._size-1: self.removeTail() return if k >= self._size: # raise IndexError("Index > len") print("Index error") return curr = self._h c = 0 while curr._next is not None: if c == k: curr._prev._next = curr._next curr._next._prev = curr._prev self._size -= 1 return else: c += 1
  • 6. curr = curr._next # This function should be used in sorted list only def insert(self, data): if self.isEmpty() or data <= self._h._data: self.addToHead(data) return if data >= self._t._data: self.addToTail(data) return curr = self._h._next while curr is not None: if data <= curr._data: newnode = self._Node(data, curr, curr._prev) curr._prev._next = newnode curr._prev = newnode self._size += 1 return else: curr = curr._next def extend(self, other): curr = other._h while curr is not None: self.addToTail(curr._data) curr = curr._next def copy(self): # shallow copy other = DLL() # e is the result of self[]; # i.e. the result of getitem function # for e in self: # other.addToTail(e) curr = self._h while curr is not None: other.addToTail(curr._data) curr = curr._next return other Ex1. Append Reverse (20 points) - Write the implementation of a member- function appendReverse(self), which appends the current list in reverse order to the end of the
  • 7. current list. This should be done in O(n). - Example: Assume that the current list =1,2,1,4,1,5 0 The function should change the current list to =1,2,1,4,1,5,5,1,4,1,2,1 Ex2. Accumulative Count (20 points) - Write the most efficient implementation of the member-function acumCount(self), which prints how long this current element exists in the remaining elements after the current element. - Example: Assume that the current list =<1,2,1,4,1,4,2,5,2; then the output is 1:2<1,2,1,4,1,4,2,5,2>2:21,2,1,4,1,4,2,5,21:14:11:04:02:15:02:0