Question

In: Computer Science

In Python: def _nodeAtIndex(self, index): """Returns the reference to the node at the given index; If...

In Python:

def _nodeAtIndex(self, index):
"""Returns the reference to the node at the given index;
If index is out of range, raise IndexError
"""
# PROBLEM 2
# You can assume that index is non-negative.
# You need to traverse the list and stop at the required index.
# YOUR CODE HERE
(THIS IS WHAT I HAVE CURRENTLY WRITTEN BUT I"M STUCK AND DON"T KNOW WHAT TO DO)

while current != None: # use a while-loop.
plist.append(current._element) # process the stored element.
count = 0 #Will give us the index of current node
if (count == index):
return (plist)
  
raise IndexError('The index is out of range')

Down below is the following code that give's more detail about the code. If you have any question's or need any more info, please don't hesitate to ask.

class SLinkedList:
"""Singly linked list with access to front and end, and with stored size.
"""

#-------------------------- nested _Node class --------------------------
class _Node:
__slots__ = '_element', '_next' # streamline memory usage

def __init__(self, element, next):
self._element = element
self._next = next

#------------------------------- queue methods -------------------------------
def __init__(self):
"""Create an empty list."""
self._head = None
self._tail = None
self._size = 0

def __len__(self):
"""Return the number of elements in the list."""
return self._size

def isEmpty(self):
"""Return True if the list is empty."""
return self._size == 0
  
# READ THIS!
def __repr__(self):
plist = []
current = self._head
# This is how to traverse a list:
while current != None: # use a while-loop.
plist.append(current._element) # process the stored element.
current = current._next # jump to the next node.
return "SLinkedList(%s)" % repr(plist)

def first(self):
"""Return but do not remove the first element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
return self._head._element
  
def deleteFirst(self):
"""Remove and return the first element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.isEmpty(): # special case when list is empty
self._tail = None # removed head had been the tail
return answer
  
def addFirst(self, e):
"""Add element e to the front of the list."""
self._head = self._Node(e, self._head) # create and link a new node
if self._tail == None: # special case when list was empty
self._tail = self._head # added head is the tail
self._size += 1
  
def addLast(self, e):
"""Add e to the end of the list."""
newest = self._Node(e, None) # node will be new tail node
if self.isEmpty():
self._head = newest # special case: previously empty
else:
self._tail._next = newest
self._tail = newest # update reference to tail node
self._size += 1
  

Solutions

Expert Solution

Updated code

class SLinkedList:
"""Singly linked list with access to front and end, and with stored size."""

#-------------------------- nested _Node class --------------------------
class _Node:
__slots__ = '_element', '_next' # streamline memory usage
def __init__(self, element, next):
self._element = element
self._next = next

#------------------------------- queue methods -------------------------------
def __init__(self):
"""Create an empty list."""
self._head = None
self._tail = None
self._size = 0

def __len__(self):
"""Return the number of elements in the list."""
return self._size

def isEmpty(self):
"""Return True if the list is empty."""
return self._size == 0

# READ THIS!
def __repr__(self):
plist = []
current = self._head
# This is how to traverse a list:
while current != None: # use a while-loop.
plist.append(current._element) # process the stored element.
current = current._next # jump to the next node.
return "SLinkedList(%s)" % repr(plist)

def first(self):
"""Return but do not remove the first element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
return self._head._element

def deleteFirst(self):
"""Remove and return the first element.
Raise EmptyError if the list is empty.
"""
if self.isEmpty():
raise EmptyError('The SLinkedList is empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.isEmpty(): # special case when list is empty
self._tail = None # removed head had been the tail
return answer

def addFirst(self, e):
"""Add element e to the front of the list."""
self._head = self._Node(e, self._head) # create and link a new node
if self._tail == None: # special case when list was empty
self._tail = self._head # added head is the tail
self._size += 1

def addLast(self, e):
"""Add e to the end of the list."""
newest = self._Node(e, None) # node will be new tail node
if self.isEmpty():
self._head =self._tail= newest # special case: previously empty
else:
self._tail._next = newest
self._tail = newest # update reference to tail node
self._size += 1

def _nodeAtIndex(self, index):
"""Returns the reference to the node at the given index;
If index is out of range, raise IndexError
"""
if(index>self._size):
raise IndexError('The index is out of range')
#if index is 1 then just retun first node
if index==1:
return self._head

count=1
current = self._head
while count!=index and current!=None:
current=current._next
count+=1
return current

code snaps for indent

If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.


Related Solutions

python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value):...
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value): pass    def pop(self): return None    def peek(self): pass    def is_empty(self): pass def stack(self): pass    def exch(self): pass    def index(self): pass    def clear(self): pass    def dup(self): pass    def equal(self): pass    def depth(self): pass    stack = PostScript() def decode(command_list): for object in command_list: if object == '=': stack.equal() elif object == 'count': stack.depth() elif object ==...
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)        &nb
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)               style = color                return    def plane(self,oil)              liquid = self.oil + self.truck(color) For the plane method, I am getting an error that the class does not define __add__ inside init so I cannot use the + operator. How do I go about this.             
Write a function parent_index_3_heap(child_index) that returns the index of the parent of the node at the...
Write a function parent_index_3_heap(child_index) that returns the index of the parent of the node at the given child_index. A None value should be returned if the child has no parent. Notes: This function is obviously for a 3-heap! The values in the heap list start at index 1 - that is the root of the heap is at index 1 in the heap list. This is for Python
''' File: pyPatientLL.py Author: JD ''' class Node: #ADT        def __init__(self, p = None):             ...
''' File: pyPatientLL.py Author: JD ''' class Node: #ADT        def __init__(self, p = None):              self.name = ""              self.ss = self.age = int(0)              self.smoker = self.HBP = self.HFD = self.points = int(0)              self.link = None              #if list not empty              if p != None:                     p.link = self        ptrFront = ptrEnd = None choice = int(0) def menu():        print( "\n\tLL Health Clinic\n\n")        print( "1. New patient\n")        print( "2. View patient by...
You are given a reference to the head node of a linked list that stores integers....
You are given a reference to the head node of a linked list that stores integers. Please print the minimum element in this linked list. The class ListNode.java contains the description of a single node in the linked list. It has a num field to store the integer number and a reference next that points to the next element in the list. The file MyList.class is a pre-defined java code, that creates a linked list. The file ListSmallest.java creates an...
You are given a reference to the root node of a binary search tree, that implements...
You are given a reference to the root node of a binary search tree, that implements a dictionary data structure. Please print all the elements in depths 500 through 510, all in sorted order. A node in a binary search tree is at depth x, if it takes x hops to get from the root. So the root is at depth 0, the children of the root are at depth 1, and so on. The class TreeNode defines a single...
You are given a reference to the head node of a linked list that stores integers....
You are given a reference to the head node of a linked list that stores integers. Please print the minimum element in this linked list. The class ListNode.java contains the description of a single node in the linked list. It has a num field to store the integer number and a reference next that points to the next element in the list. The file MyList.class is a pre-defined java code, that creates a linked list. The file ListSmallest.java creates an...
You are given a reference to the head node of a linked list that stores integers....
You are given a reference to the head node of a linked list that stores integers. Please print the minimum element in this linked list. The class ListNode.java contains the description of a single node in the linked list. It has a num field to store the integer number and a reference next that points to the next element in the list. The file MyList.class is a pre-defined java code, that creates a linked list. The file ListSmallest.java creates an...
You are given a reference to the head node of a linked list that stores integers....
You are given a reference to the head node of a linked list that stores integers. Please print the minimum element in this linked list. The class ListNode.java contains the description of a single node in the linked list. It has a num field to store the integer number and a reference next that points to the next element in the list. The file MyList.class is a pre-defined java code, that creates a linked list. The file ListSmallest.java creates an...
You are given a reference to the head node of a linked list that stores integers....
You are given a reference to the head node of a linked list that stores integers. Please print the minimum element in this linked list. The class ListNode.java contains the description of a single node in the linked list. It has a num field to store the integer number and a reference next that points to the next element in the list. The file MyList.class is a pre-defined java code, that creates a linked list. The file ListSmallest.java creates an...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT