Question

PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand

LinkedList ADT:

class myLinkedList:
    def __init__(self):
        self.__head = None
       
self.__tail = None
       
self.__size = 0

    def insert(self, i, data):
        if self.isEmpty():
            self.__head = listNode(data)
            self.__tail = self.__head
        elif i <= 0:
            self.__head = listNode(data, self.__head)
        elif i >= self.__size:
            self.__tail.setNext(listNode(data))
            self.__tail = self.__tail.getNext()
        else:
            current = self.__getIthNode(i - 1)
            current.setNext(listNode(data, current.getNext()))
            if current == self.__tail:
                self.__tail = self.__tail.getNext()
        self.__size += 1

    def __getIthNode(self, i):
        current = self.__head
        count = 0
        while current is not None and count < i:
            count = count + 1
            current = current.getNext()
        return current

    def __str__(self):
        current = self.__head
        result = ""
       
while current is not None:
            result = result + " " + str(current.getData())
            current = current.getNext()
        return result

    #returns True if list is empty, else False
   
def isEmpty(self):
        return self.__head==None

   
#returns the length
   
def __len__(self):
        '''count = 0
        current=self.__head
        #counting number of nodes
        while current is not None:
            count = count + 1
            current = current.getNext()
        #returning count
        return count'''
       
return self.__size

    #adds to the front
   
def prepend(self, item):
        #adding the item at index 0
       
self.insert(0,item)

    #adds to the rear
   
def append(self,item):
        #adding the item at the end
       
self.insert(len(self),item)

    #removes and returns the element at index i
   
def pop(self, i):
        #validating index
       
if i<0 or i>=len(self):
            return None #invalid index
        #finding ith node
       
node=self.__getIthNode(i)
        #if it is head, updating head node
        
if node==self.__head:
            self.__head=self.__head.getNext()
            self.__size-=1
            return node.getData() #returning removed data
        #finding previous node
       
prev=self.__getIthNode(i-1)
        #linking node at i+1 as next node of node at i-1
       
prev.setNext(node.getNext())
        self.__size -= 1
        return node.getData() #returning removed data

    #helps to access data by index (using [])
   
def __getitem__(self, index):
        #returning data of node at index
       
return self.__getIthNode(index).getData()

    #helps to set data by index (using [])
   
def __setitem__(self, index, value):
        #updates the data of node at index
       
self.__getIthNode(index).setData(value)

    #returns the index of an item, if exists
   
def find(self,item):
        #looping and comparing each item with target
       
for i in range(len(self)):
            if self.__getitem__(i)==item:
                #found
               
return i
        return -1 #not found

student class ADT:

class Student:
def __init__(self, id=None, name=""):
self.id = id
self.name = name

def getID(self):
return self.id

def getName(self):
return self.name

def setID(self, id):
self.id = id

def setName(self, name):
self.name = name

def __str__(self):
#print out
print(str(self.id) + "(" + self.name+")")


def __cmp__(self,other_id):
ot_id = other_id.getID()
if (self.id < ot_id):
p = -1
elif (self.id > ot_id):
p = 1
elif (self.id == ot_id):
p = 0
return p

def __eq__(self,other_id):
x = self.__cmp__(other_id)
if x == 0:
print(True)
else:
print(False)

def __ne__(self,other_id):
x = self.__cmp__(other_id)
if x == 0:
print(False)
else:
print(True)

def __lt__(self,other_id):
x = self.__cmp__(other_id)
if x == -1:
print(True)
else:
print(False)

def __le__(self,other_id):
x = self.__cmp__(other_id)
if x == 0 or x==-1:
print(True)
else:
print(False)

def __gt__(self,other_id):
k = self.__cmp__(other_id)
if (k == 1):
print(True)
else:
print(False)

def __ge__(self,other_id):
k = self.__cmp__(other_id)
if (k == 0 or k==1):
print(True)
else:

print(False)

LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below)

  1. Imports the Student class
  2. Imports the time module
  3. Imports the myLinkedList class
  1. Create a main() function which:
    1. Open the list of names files and read the student information and puts them into a list of Student's. You will need to use the strip() function on the line of input from the file to remove extra white space, then use split() using a tab as a deliminator to split the line of input into the student ID and name. The ID should also be converted to an integer so that it can more easily be compared with other IDs.
    2. Close the 1st file
    3. Open the search file and read each line of the 2nd file and create a new Student record (except that it will have only an ID and not a name). Search for a match in the list of Student's and print the record that matches. If there is no match, then print an appropriate message. You created a function the the myLinkedList class that should help with this.
    4. An sample output might looks something like this:

      Found student record: 7654321 (Ashley Tomkin)
      Found student record: 2345678 (Katie Smith)
      Student ID: 1234567 not found
      Found student record: 3456789 (Matt Simpson)
      Student ID 9876543 not found
  2. You should first work with the short versions of the input file before moving on to the medium versions. After your program is successfully capable to adding all of the students to the Linked List and is able to read the student IDs in the search file and print an appropriate message, then you want to time how long it takes.  
    1. First, comment out the printing of the messages, so that you aren't timing that.  
    2. Surround the section of code you want to time with two time stamps (calls to the time.time() method. The elapse time can be calculated by taking the difference between the two time stamps. For example:
           startTime = time.time()
           # Do the stuff you want to time

           endTime = time.time()
           print("Time to do <whatever> " + format(endTime - startTime, "6.4f") + " seconds.")
    1. Time how long it takes to insert the student records into the Linked List as well as search for them using the medium versions of the files. For example, you might something like this:

      The time to insert 10000 student records into a Linked List = 0.0341 seconds.
      The time to search 10000 student records from a Linked List = 23.9849 seconds.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

here is the answer ............

class myLinkedList: #this is for the creation of linked list..
    def __init__(self):
        self.__head = None
       
self.__tail = None
       
self.__size = 0

    def insert(self, i, data): #this function is used for the inserting the data in the linked list...
        if self.isEmpty():
            self.__head = listNode(data)
            self.__tail = self.__head
        elif i <= 0:
            self.__head = listNode(data, self.__head)
        elif i >= self.__size:
            self.__tail.setNext(listNode(data))
            self.__tail = self.__tail.getNext()
        else:
            current = self.__getIthNode(i - 1)
            current.setNext(listNode(data, current.getNext()))
            if current == self.__tail:
                self.__tail = self.__tail.getNext()
        self.__size += 1

    def __getIthNode(self, i): #this is for the getting requested node..
        current = self.__head
        count = 0
        while current is not None and count < i:
            count = count + 1
            current = current.getNext()
        return current

    def __str__(self): #this is for the current head node
        current = self.__head
        result = ""
       
while current is not None:
            result = result + " " + str(current.getData())
            current = current.getNext()
        return result

    #returns True if list is empty, else False
   
def isEmpty(self):
        return self.__head==None

   
#returns the length
   
def __len__(self):
        '''count = 0
        current=self.__head
        #counting number of nodes
        while current is not None:
            count = count + 1
            current = current.getNext()
        #returning count
        return count'''
       
return self.__size

    #adds to the front
   
def prepend(self, item):
        #adding the item at index 0
       
self.insert(0,item)

    #adds to the rear
   
def append(self,item):
        #adding the item at the end
       
self.insert(len(self),item)

    #removes and returns the element at index i
   
def pop(self, i):
        #validating index
       
if i<0 or i>=len(self):
            return None #invalid index
        #finding ith node
       
node=self.__getIthNode(i)
        #if it is head, updating head node
        
if node==self.__head:
            self.__head=self.__head.getNext()
            self.__size-=1
            return node.getData() #returning removed data
        #finding previous node
       
prev=self.__getIthNode(i-1)
        #linking node at i+1 as next node of node at i-1
       
prev.setNext(node.getNext())
        self.__size -= 1
        return node.getData() #returning removed data

    #helps to access data by index (using [])
   
def __getitem__(self, index):
        #returning data of node at index
       
return self.__getIthNode(index).getData()

    #helps to set data by index (using [])
   
def __setitem__(self, index, value):
        #updates the data of node at index
       
self.__getIthNode(index).setData(value)

    #returns the index of an item, if exists
   
def find(self,item):
        #looping and comparing each item with target
       
for i in range(len(self)):
            if self.__getitem__(i)==item:
                #found
               
return i
        return -1 #not found

student class ADT:

class Student:
def __init__(self, id=None, name=""):
self.id = id
self.name = name

def getID(self):
return self.id

def getName(self):
return self.name

def setID(self, id):
self.id = id

def setName(self, name):
self.name = name

def __str__(self):
#print out
print(str(self.id) + "(" + self.name+")")


def __cmp__(self,other_id):
ot_id = other_id.getID()
if (self.id < ot_id):
p = -1
elif (self.id > ot_id):
p = 1
elif (self.id == ot_id):
p = 0
return p

def __eq__(self,other_id):
x = self.__cmp__(other_id)
if x == 0:
print(True)
else:
print(False)

def __ne__(self,other_id):
x = self.__cmp__(other_id)
if x == 0:
print(False)
else:
print(True)

def __lt__(self,other_id):
x = self.__cmp__(other_id)
if x == -1:
print(True)
else:
print(False)

def __le__(self,other_id):
x = self.__cmp__(other_id)
if x == 0 or x==-1:
print(True)
else:
print(False)

def __gt__(self,other_id):
k = self.__cmp__(other_id)
if (k == 1):
print(True)
else:
print(False)

def __ge__(self,other_id):
k = self.__cmp__(other_id)
if (k == 0 or k==1):
print(True)
else:

print(False)

Add a comment
Know the answer?
Add Answer to:
PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None   

    PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None        self.__size = 0    # Return the head element in the list    def getFirst(self):        if self.__size == 0:            return None        else:            return self.__head.element        # Return the last element in the list    def getLast(self):        if self.__size == 0:            return None        else:            return self.__tail.element    # Add an element to the beginning of the list    def addFirst(self, e):        newNode = Node(e) # Create a new node        newNode.next = self.__head # link...

  • Task 2: SecretWord class: Download and save a copy of LinkedLists.py (found at the bottom of...

    Task 2: SecretWord class: Download and save a copy of LinkedLists.py (found at the bottom of this assignment page on eClass). In this file, you have been given the complete code for a LinkedList class. Familiarize yourself with this class, noticing that it uses the Node class from Task 1 and is almost identical to the SLinkedList class given in the lectures. However, it also has a complete insert(pos, item) method (which should be similar to the insert method you...

  • I am having trouble with my Python code in this dictionary and pickle program. Here is...

    I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...

  • I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to...

    I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...

  • Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display,...

    Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display, remove methods. You may use default arguments and/or helper functions. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list """ if self.head is...

  • Python 3: Write a LinkedList method named contains, that takes a value as a parameter and...

    Python 3: Write a LinkedList method named contains, that takes a value as a parameter and returns True if that value is in the linked list, but returns False otherwise. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list...

  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i...

    I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i am recieving says that in line 61 list index is out of range. kindly someone help me with it as soon as possible. Below is the program kindly check and correct it. Thanks! class Animal: def __init__(self, name, types, species, mass): self.name=name self.type=types...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT