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 of the GradeItem in a grading scheme
:param scored: the scored obtained in the grade item
:param out_of: the maximum possible score for the grade item
"""
self.weight = weight
self.scored = scored
self.out_of = out_of
def __str__(self):
"""
Purpose:
Represent the Grade object as a string.
If the item has not been assessed yet, N/A is used.
This function gets called by str().
Return:
A string representation of the Grade.
"""
if self.scored is None or self.out_of is None:
return 'N/A'
else:
return str(self.scored) + '/' + str(self.out_of)
def record_outcome(self, n, d):
"""
Purpose:
Record the outcome of the GradeItem.
Preconditions:
:param n: The score obtained on the item
:param d: The maximum score on the item
Post-conditions:
Changes the data stored in the GradeItem
Return: None
"""
self.scored = n
self.out_of = d
def contribution(self):
"""
Purpose:
Calculate and return the contribution this GradeItem makes
to a grading scheme. If the item has not been assessed,
a value of zero is returned.
Return:
The weighted contribution of the GradeItem.
"""
if self.scored is None or self.out_of is None:
return 0
else:
return self.weight * self.scored / self.out_of
class StudentRecord(object):
def __init__(self, first, last, st_number):
"""
Purpose: Initialize the Student object.
Preconditions:
:param first: The student's first name, as a string
:param last: The student's last name, as a string
:param st_number: The student's id number, as a string
"""
self.first_name = first
self.last_name = last
self.id = st_number
self.midterm = None
self.labs = []
def drop_lowest(self, grades):
"""
Purpose:
Sets the weight of the lowest grade in grades to zero.
Pre-conditions:
:param grades: a list of GradeItems
Post-conditions:
One of the grade items has its weight set to zero
Return:
:return: None
"""
pass
def calculate(self):
"""
Purpose:
Calculate the final grade in the course.
Return:
The final grade.
"""
return round(self.midterm.contribution()
+ sum([b.contribution() for b in self.labs]))
def display(self):
"""
Purpose:
Display the information about the student, including
all lab and assignment grades, and the calculation of the total grade.
:return:
"""
print("Student:", self.first_name, self.last_name,
'(' + self.id + ')')
print("\tCourse grade:", self.calculate())
print('\tMidterm:', str(self.midterm))
#
print('\tLabs:', end=" ")
for g in self.labs:
if g.weight == 0:
print('[' + str(g) + ']', end=' ')
else:
print(str(g), end=' ')
print()
def read_student_record_file(filename):
"""
Purpose:
Read a student record file, containing information about the student.
Line 1: Out of: the maximum score for the grade items
Line 2: Weight: the weight of the grade items in the grading scheme
Lines 3...: Student records as follows:
Student Number, Lastname, Firstname, 10 lab marks, 10 assignment marks, midterm, final
Pre-conditions:
:param filename: A text file, comma-separated, with the above format.
Return:
:return: A list of StudentRecords constructed from the named file.
"""
f = open(filename)
# Second line tells us what the grade items are out of
out_of_line = f.readline().rstrip().split(',')
out_of = [int(i) for i in out_of_line[1:]]
lab_out_of = out_of[0:10]
assignments_out_of = out_of[10:20]
mt_out_of = out_of[20]
final_out_of = out_of[21]
# Third line tells us the weight of each item
weight_line = f.readline().rstrip().split(',')
weights = [int(i) for i in weight_line[1:]]
lab_weights = weights[0:10]
assignment_weights = weights[10:20]
mt_weight = weights[20]
final_weight = weights[21]
# Read all the students in the file:
students = list()
for line in f:
student_line = line.rstrip().split(',')
student = StudentRecord(student_line[2],student_line[1],student_line[0])
labs = [int(lab) for lab in student_line[3:13]]
assignments = [int(a) for a in student_line[13:23]]
for g,o,w in zip(labs,lab_out_of,lab_weights):
student.labs.append(GradeItem(w,g,o))
student.midterm = GradeItem(mt_weight,int(student_line[23]),mt_out_of)
students.append(student)
return students
if __name__ == '__main__':
course = read_student_record_file('students.txt')
# display the students
print('------------- Before ---------------')
for s in course:
s.display()
# drop lowest lab for all students
for s in course:
s.drop_lowest(s.labs)
# display the students
print('------------- After ----------------')
for s in course:
s.display()
***Students.txt file below***
Out
of,4,4,4,4,4,4,4,4,4,4,41,50,35,60,70,55,45,50,60,60,60,90
Weights,1,1,1,1,1,1,1,1,1,1,4,4,4,4,4,4,4,4,4,4,10,40
3111332,Einstein,Albert,4,4,3,4,4,3,4,3,3,4,39,46,34,58,65,45,25,10,40,35,35,50
3216842,Curie,Marie,3,4,3,4,3,4,1,4,1,4,41,45,30,50,61,48,37,43,55,58,55,85
*The solution code returns 78.5 of avg when the lowest grades are NOT dropped from the student.txt file. On the other hand, if they ARE dropped for BOTH labs and assignments, the avg becomes 80.5
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 of the GradeItem in a grading scheme
:param scored: the scored obtained in the grade item
:param out_of: the maximum possible score for the grade item
"""
self.weight = weight
self.scored = scored
self.out_of = out_of
def __str__(self):
"""
Purpose:
Represent the Grade object as a string.
If the item has not been assessed yet, N/A is used.
This function gets called by str().
Return:
A string representation of the Grade.
"""
if self.scored is None or self.out_of is None:
return 'N/A'
else:
return str(self.scored) + '/' + str(self.out_of)
def record_outcome(self, n, d):
"""
Purpose:
Record the outcome of the GradeItem.
Preconditions:
:param n: The score obtained on the item
:param d: The maximum score on the item
Post-conditions:
Changes the data stored in the GradeItem
Return: None
"""
self.scored = n
self.out_of = d
def contribution(self):
"""
Purpose:
Calculate and return the contribution this GradeItem makes
to a grading scheme. If the item has not been assessed,
a value of zero is returned.
Return:
The weighted contribution of the GradeItem.
"""
if self.scored is None or self.out_of is None:
return 0
else:
return self.weight * self.scored / self.out_of
class StudentRecord(object):
def __init__(self, first, last, st_number):
"""
Purpose: Initialize the Student object.
Preconditions:
:param first: The student's first name, as a string
:param last: The student's last name, as a string
:param st_number: The student's id number, as a string
"""
self.first_name = first
self.last_name = last
self.id = st_number
self.midterm = None
self.labs = []
self.final_exam = None
self.assignments = []
def drop_lowest(self, grades):
"""
Purpose:
Sets the weight of the lowest grade in grades to zero.
Pre-conditions:
:param grades: a list of GradeItems
Post-conditions:
One of the grade items has its weight set to zero
Return:
:return: None
"""
if(len(grades) > 0):
minIndex = 0
totalWeight = sum([g.weight for g in grades]) # calculate the total weight
# loop to get the minimum scored grade
for i in range(1,len(grades)):
if grades[i].scored < grades[minIndex].scored:
minIndex = i
grades[minIndex].weight = 0
newWeight = (float(totalWeight))/(len(grades)-1) # calculate the new weight after removing the lowest grade
# loop to redistribute the weights
for i in range(1,len(grades)):
if i != minIndex:
grades[i].weight= newWeight
def calculate(self):
"""
Purpose:
Calculate the final grade in the course.
Return:
The final grade.
"""
return round(self.midterm.contribution()
+ sum([b.contribution() for b in self.labs]) + self.final_exam.contribution() + sum([a.contribution() for a in self.assignments]))
def display(self):
"""
Purpose:
Display the information about the student, including
all lab and assignment grades, and the calculation of the total grade.
:return:
"""
print("Student:", self.first_name, self.last_name,'(' + self.id + ')')
print("\tCourse grade:", self.calculate())
print('\tMidterm:', str(self.midterm))
print('\tLabs:', end=" ")
for g in self.labs:
if g.weight == 0:
print('[' + str(g) + ']', end=' ')
else:
print(str(g), end=' ')
print()
print('\tAssignments : '),
for g in self.assignments:
if g.weight == 0:
print('[' + str(g) + ']', end=' ')
else:
print(str(g), end=' ')
print()
print('\tFinal Exam : ',str(self.final_exam))
def read_student_record_file(filename):
"""
Purpose:
Read a student record file, containing information about the student.
Line 1: Out of: the maximum score for the grade items
Line 2: Weight: the weight of the grade items in the grading scheme
Lines 3...: Student records as follows:
Student Number, Lastname, Firstname, 10 lab marks, 10 assignment marks, midterm, final
Pre-conditions:
:param filename: A text file, comma-separated, with the above format.
Return:
:return: A list of StudentRecords constructed from the named file.
"""
f = open(filename)
# First line tells us what the grade items are out of
out_of_line = f.readline().rstrip().split(',')
out_of = [int(i) for i in out_of_line[1:]]
lab_out_of = out_of[0:10]
assignments_out_of = out_of[10:20]
mt_out_of = out_of[20]
final_out_of = out_of[21]
# Second line tells us the weight of each item
weight_line = f.readline().rstrip().split(',')
weights = [int(i) for i in weight_line[1:]]
lab_weights = weights[0:10]
assignment_weights = weights[10:20]
mt_weight = weights[20]
final_weight = weights[21]
# Read all the students in the file:
students = list()
for line in f:
student_line = line.rstrip().split(',')
student = StudentRecord(student_line[2],student_line[1],student_line[0])
labs = [int(lab) for lab in student_line[3:13]]
assignments = [int(a) for a in student_line[13:23]]
for g,o,w in zip(labs,lab_out_of,lab_weights):
student.labs.append(GradeItem(w,g,o))
for g,o,w in zip(assignments,assignments_out_of,assignment_weights):
student.assignments.append(GradeItem(w,g,o))
student.midterm = GradeItem(mt_weight,int(student_line[23]),mt_out_of)
student.final_exam = GradeItem(final_weight,int(student_line[24]),final_out_of)
students.append(student)
return students
if __name__ == '__main__':
course = read_student_record_file('students.txt')
# display the students
print('------------- Before ---------------')
for s in course:
s.display()
#calculate class average
total = 0
for s in course:
total += s.calculate()
avg = total/len(course)
print('Average : '+str(avg))
# drop lowest lab and lowest assignment for all students
for s in course:
s.drop_lowest(s.labs)
s.drop_lowest(s.assignments)
# display the students
print('------------- After ----------------')
for s in course:
s.display()
#calculate class average
total = 0
for s in course:
total += s.calculate()
avg = total/len(course)
print('Average : '+str(avg))
#end of program
Code Screenshot:






PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything...
in python im trying to get this to print to the file i it created def calculateTotal(): filename = input("Enter a name for the file : ")#ask users for a name for file no_of_students = int(input("Enter the number of students in class : ")) data = [] with open(filename,"w+") as f: for index in range(no_of_students): grades = input("Enter Name of student plus grade :").split() # store the student data in array "data" data.append(grades) # store the total grades in "total"...
Write this code on python 3 only.
Suppose class Student represents information about students in a course. Each student has a name and a list of test scores. The Student class should allow the user to view a student's name, view a test score at a given position, view the highest test score, view the average test score, and obtain a string representation of the student's information. When a Student object is created, the user supplies the student's name and...
Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class. Since there are no setters and getters, we use the attributes directly. This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...
Must be in Python 3
exercise_2.py
# Define the Student class
class Student():
# Initialize the object properties
def __init__(self, id, name, mark):
# TODO
# Print the object as an string
def __str__(self):
return ' - {}, {}, {}'.format(self.id, self.name, self.mark)
# Check if the mark of the input student is greater than the
student object
# The output is either True or False
def is_greater_than(self, another_student):
# TODO
# Sort the student_list
# The output is the sorted...
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...
Please code in Python Revise the AbstractBag class so that it behaves as a subclass of AbstractCollection provided in the file abstractcollection.py. Abstractcollection.py code: class AbstractCollection(object): """An abstract collection implementation.""" # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self.size = 0 if sourceCollection: for item in sourceCollection: self.add(item) # Accessor methods def isEmpty(self): """Returns True if len(self) == 0, or False otherwise.""" return len(self) == 0...
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,...
Python3 programming help needed LAB*: Program: Online shopping cart (continued) Need the below code edited to run properly for the lab.. class ItemPurchase: def __init__(self, nameitem='none', item_prc=0, item_quntity=0, item_descrp = 'none'): self.nameitem = nameitem self.item_prc = item_prc self.item_quntity = item_quntity self.item_descrp = item_descrp def print_itemvaluecost(self): string = '{} {} @ ${} = ${}'.format(self.nameitem, self.item_quntity, self.item_prc(self.item_quntity * self.item_prc)) valuecost = self.item_quntity * self.item_prc return string, valuecost def print_itemdescription(self): string...
Python3 programming help needed LAB*: Program: Online shopping cart (continued) Need the below code edited to run properly for the lab.. class ItemPurchase: def __init__(self, nameitem='none', item_prc=0, item_quntity=0, item_descrp = 'none'): self.nameitem = nameitem self.item_prc = item_prc self.item_quntity = item_quntity self.item_descrp = item_descrp def print_itemvaluecost(self): string = '{} {} @ ${} = ${}'.format(self.nameitem, self.item_quntity, self.item_prc(self.item_quntity * self.item_prc)) valuecost = self.item_quntity * self.item_prc return string, valuecost def print_itemdescription(self): string = '{}: {}'.format(self.nameitem, self.item_descrp) print(string , end='\n') return string class Shopping_Cart: #Parameter...
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",...