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", line 65, in gpaSort
if maxgpa[gpa1][2] < maxgpa[gpa2][2]:
TypeError: 'Person' object does not support indexing
Current Code:
class Person(object):
def __init__(self, name, ID, age, gpa):
self.name = name
self.id = ID
self.age = age
self.gpa = gpa
def __str__(self):
output = "\n\nStudent Record for ID# {}\n".format(self.id)
output += "Name: {} \nAge: {} \nGPA: {}".format(self.name, self.age, self.gpa)
return output
####################################################################################################
class List(object):
def __init__(self):
self.studentList = []
self.getList()
def getList(self):
try:
file = open("students.txt", "r")
name = file.readline().rstrip("\n")
while len(name) != 0:
id = int(file.readline().rstrip("\n"))
age = int(file.readline().rstrip("\n"))
gpa = float(file.readline().rstrip("\n"))
self.studentList.append(Person(name, id, age, gpa))
name = file.readline().rstrip("\n")
except:
print("File could not be opened")
def spaces(self, name):
tab = 24 - len(name)
temp = ''
for j in range(tab):
temp += " "
return temp
def displayStudent(self, index):
print(self.studentList[index])
def display(self, listInfo):
print('\nDisplaying {}'.format(listInfo))
print("\nStudent ID# Student Name Age GPA")
print("=============================================================")
for person in self.studentList:
print("{} {}".format(person.id, person.name), self.spaces(person.name),
"{} {}".format(person.age, person.gpa))
def swap(self, x, y):
"""swap the person objects in the studentList at index x and y"""
temp = self.studentList[x]
self.studentList[x] = self.studentList[y]
self.studentList[y] = temp
def gpaSort(self):
"""sort the students list in descending order of GPA"""
"""Bubble sort"""
maxgpa = list(self.studentList)
for gpa1 in range(len(maxgpa)):
for gpa2 in range(len(maxgpa)-1):
if maxgpa[gpa2][0] < maxgpa[gpa2 + 1][0]:
maxgpa[gpa2], maxgpa[gpa2 + 1] = maxgpa[gpa2 + 1], maxgpa[gpa2]
return maxgpa
def ageSort(self):
"""sort the students list in ascending order of age"""
"""selection sort"""
minage = list(self.studentList)
for age1 in range(len(minage)):
for age2 in range(age1 + 1, len(minage)):
if minage[age1][2] > minage[age2][2]:
minage[age1], minage[age2] = minage[age2], minage[age1]
return minage
def idSort(self):
"""sort the student list in descending order of id numbers"""
"""Insertion sort"""
maxid = list(self.studentList)
for idindex in range(1, len(maxid)):
while(idindex > 0):
if maxid[idindex][3] < maxid[idindex - 1][3]:
break
maxid[idindex], maxid[idindex -1 ] = maxid[idindex - 1], maxid[idindex]
idindex -= 1
return maxid
def search(self, studentID):
"""search for a student in the student list with the passed idNumber
return the index of the student if found, return -1 if not found"""
pass
############################################################################################
def main():
studentArray = List()
studentArray.display("UNSORTED LIST OF STUDENTS")
input("\nPRESS ENTER TO SORT BY GPA")
studentArray.gpaSort()
studentArray.display("STUDENTS SORTED IN DESCENDING ORDER BY GPA")
input("\nPRESS ENTER TO SORT BY AGE")
studentArray.ageSort()
studentArray.display("STUDENTS SORTED IN ASCENDING ORDER BY AGE")
input("\nPRESS ENTER TO SORT BY ID#")
studentArray.idSort()
studentArray.display("STUDENTS SORTED IN DESCENDING ORDER BY ID#")
input("PRESS ENTER TO CONTINUE")
if hasattr(studentArray, "search"):
try:
idNumber = int(input("\n\nEnter the ID number of a student to search for: "))
location = studentArray.search(idNumber)
if location == -1:
print("Student Not Found")
else:
studentArray.displayStudent(location)
except ValueError:
print("Run it again and type an integer value")
input("\n\nPRESS ENTER TO QUIT")
main()
def gpaSort(self):
"""sort the students list in descending order of GPA"""
"""Bubble sort"""
maxgpa = list(self.studentList)
for gpa1 in range(len(maxgpa)):
for gpa2 in range(len(maxgpa)-1):
if maxgpa[gpa2].gpa < maxgpa[gpa2 + 1].gpa:
maxgpa[gpa2], maxgpa[gpa2 + 1] = maxgpa[gpa2 + 1], maxgpa[gpa2]
return maxgpa
def ageSort(self):
"""sort the students list in ascending order of age"""
"""selection sort"""
minage = list(self.studentList)
for age1 in range(len(minage)):
for age2 in range(age1 + 1, len(minage)):
if minage[age1].age > minage[age2].age:
minage[age1], minage[age2] = minage[age2], minage[age1]
return minage
def idSort(self):
"""sort the student list in descending order of id numbers"""
"""Insertion sort"""
maxid = list(self.studentList)
for idindex in range(1, len(maxid)):
while(idindex > 0):
if maxid[idindex].id < maxid[idindex - 1].id:
break
maxid[idindex], maxid[idindex -1 ] = maxid[idindex - 1], maxid[idindex]
idindex -= 1
return maxid
===========================
The issue is in above 3 functions.. When you want to compare the gpa, then you need to say:
"maxgpa[gpa2].gpa" not "maxgpa[gpa2][0]", Because there is no index 0, in person object.. Rather person object has attributes such as id, gpa, name etc..
maxgpa is a list of persons.. So when you say maxgpa[gpa2] it means, you got a person object.. On this you say .gpa, which means you are accessing the gpa attribute of person and comparing that.
Please upvote if it helps. Thanks!
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...
My tests for sorting algorithms are not working. sorting.py has 6 sorting algorithms and test_sorting.py has test cases to run those algorithms, but test cases are not working. please correct the errors in test_sorting.py file so that it can test all the sorting algorithms. WARNING: DON'T COPY AND PASTE THE QUESTION IN ANSWER. I WILL REPORT YOU. sorting.py # 1. selection sort # 2. insertion sort # 3. shell sort # 4. heap sort # 5. merge sort # 6....
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,...
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...
In C++
Write a menu driven C++ program to read a file containing
information for a list of Students, process the data, then present
a menu to the user, and at the end print a final report shown
below. You may(should) use the structures you developed for the
previous assignment to make it easier to complete this assignment,
but it is not required.
Required Menu Operations are:
Read Students’ data from a file to update the list (refer to
sample...
PYTHON 3 Object Oriented Programming
***a9q3.py file below***
class GradeItem(object):
# A Grade Item is anything a course uses in a grading scheme,
# like a test or an assignment. It has a score, which is assessed by
# an instructor, and a maximum value, set by the instructor, and a weight,
# which defines how much the item counts towards a final grade.
def __init__(self, weight, scored=None, out_of=None):
"""
Purpose:
Initialize the GradeItem object.
Preconditions:
:param weight: the weight...
Rework this project to include a class. As explained in class, your project should have its functionalities moved to a class, and then create each course as an object to a class that inherits all the different functionalities of the class. You createclass function should be used as a constructor that takes in the name of the file containing the student list. (This way different objects are created with different class list files.) Here is the code I need you...