Modified gpasort program
Program plan:
- Import the necessary modules in “grade_sort.py” file.
- Define the “make_Student()” function,
- Returns student record values to the caller.
- Define the “read_Students()” function,
- Returns the list of student record to the caller.
- Define the “write_Students()” function,
- Write the student record.
- Define the “main()” function,
- Get the input file.
- Read the students record for the input file.
- Make a “while” loop for “True”.
- Get the type of input to sort.
- Get the type of ordering from the user.
- Check whether the type is “GPA” using “if”.
- If it is true, sort the data based on the “GPA”.
- Rename the file name.
- Check whether the ordering is "D"
-
- If it is true, reverse the data.
- Use “break” to exit.
- Check whether the type is “name” using “elif”.
- If it is true, sort the data based on the “name”.
- Rename the file name.
- Check whether the ordering is "D"
-
- If it is true, reverse the data.
- Use “break” to exit.
- Check whether the type is “credits” using “if”.
- If it is true, sort the data based on the “credits”.
- Rename the file name.
- Check whether the ordering is "D"
-
- If it is true, reverse the data.
- Use “break” to exit.
-
-
- Write the data into the output file.
-
- Check whether the type is “GPA” using “if”.
- Create a class Student in “gpa.py” file,
- Define the “_init_()” method.
- Assign name hours and GPoints.
-
-
-
- Define the “get_Name()” method.
- Return the name.
- Define the “get_Hours()” method.
- Return hours.
- Define the “getQ_Points()” method.
- Return GPoints.
- Define the “gpa()” method.
- Return gpa
- Define the “make_Student()” method.
- Return name, hours, and grade points.
- Define the “main()” function.
- Define the “get_Name()” method.
-
-
-
- Assign name hours and GPoints.
- Define the “_init_()” method.
- Call the “main()” function.
Explanation of Solution
Program:
File name: “gpasort.py”
#Import required module
from gpa import Student
#Define the function make_Student()
def make_Student(info_Str):
#Make multiple assignment
Name, Hours, Gpoints = info_Str.split("\t")
#Return constructor
return Student(Name, Hours, Gpoints)
#Define the function read_Students()
def read_Students(file_name):
#Open the input file for reading
in_file = open(file_name, 'r')
#Create an empty list
Students = []
#Create for loop to iterate over all lines in a file
for line in in_file:
#Append the line in a list
Students.append(make_Student(line))
#Close the input file
in_file.close()
#Return the list
return Students
#Define the function write_Students()
def write_Students(Students, file_name):
#Open output file to write
out_file = open(file_name, 'w')
#Create a for loop to iterate over list
for s in Students:
#Print output
print("{0}\t{1}\t{2}".format(s.get_Name(), s.get_Hours(), s.getQ_Points()), file = out_file)
#Close the output file
out_file.close()
#Define the main() function
def main():
#Print the string
print("This program sorts student grade information by GPA, name, or credits.")
#Get the input file
file_name = 'gpa1.txt'
#Assign the data return from read_Students()
data = read_Students(file_name)
#Create "while" loop
while True:
#Get the type
x = (input('Type "GPA", "name", or "credits" >>> '))
#Get the type of ordering
m = (input('Type "A" for ascending, "D" for descending.'))
#Check whether the type is "GPA"
if x == 'GPA':
#Sort the data based on the gpa
data.sort(key=Student.gpa)
#Rename the file name
s = "_(GPA)"
#Check whether the ordering is "D"
if m == "D":
#Reverse the data
data.reverse()
#Use break to exit
break
#Check whether the type is "name"
elif x == 'name':
#Sort the data based on the name
data.sort(key=Student.get_Name)
#Rename the file name
s = "_(name)"
#Check whether the ordering is "D"
if m == "D":
#Reverse the data
data.reverse()
#Use break to exit
break
#Check whether the type is "credits"
elif x == 'credits':
#Sort the data based on the credits
data.sort(key=Student.getQ_Points)
#Rename the file name
s = "_(credits)"
#Check whether the ordering is "D"
if m == "D":
#Reverse the data
data.reverse()
#Use break to exit
break
#Otherwise
else:
#Print the string
print("Please try again.")
#Assign the output file
filename = "GPA2" + s + ".py"
#Write the data into output file
write_Students(data, filename)
#Print output file
print("The data has been written to", filename)
#Call the main function
if __name__ == '__main__': main()
File name: “gpa.py”
#Create a class Student
class Student:
#Define _init_() method
def __init__(self, Name, Hours, Gpoints):
self.Name = Name
self.Hours = float(Hours)
self.Gpoints = float(Gpoints)
#Define get_Name() method
def get_Name(self):
#Return the name
return self.Name
#Define get_Hours()
def get_Hours(self):
#return hours
return self.Hours
#Define getQ_Points()
def getQ_Points(self):
#return grade points
return self.Gpoints
#Define the funcition gpa()
def gpa(self):
#return the value
return self.Gpoints / self.Hours
#Define the function make_Student()
def make_Student(info_Str):
#Make multiple assignment
Name, Hours, Gpoints = info_Str.split("\t")
#Return the constructor
return Student(Name, Hours, Gpoints)
#Define the main() function
def main():
#Open the input file for reading
file_name = input("Enter the name of the grade file: ")
in_file = open(file_name, 'r')
#Set best to the record for the first student in the file
best = make_Student(in_file.readline())
#Process lines of the file using "for" loop
for line in in_file:
#Make the line of file into a student record
s = make_Student(line)
#Checck whether the student is best so far
if s.gpa() > best.gpa():
#Assign the best student record
best = s
#Close the input file
in_file.close()
#Print information about the best student
print("The best student is:", best.get_Name())
print("Hours:", best.get_Hours())
print("GPA:", best.gpa())
if __name__ == '__main__':
#Call the main() function
main()
Contents of “gpa1.txt”
Adams, Henry 127 228
Computewell, Susan 100 400
DibbleBit, Denny 18 41.5
Jones, Jim 48.5 155
Smith, Frank 37 125.33
Screenshot of output file “GPA2.py” before execution:
Output:
This program sorts student grade information by GPA, name, or credits.
Type "GPA", "name", or "credits" >>> name
Type "A" for ascending, "D" for descending.D
The data has been written to GPA2_(name).py
>>>
Screenshot of output file “GPA2_(name).py after execution:
Additional output:
This program sorts student grade information by GPA, name, or credits.
Type "GPA", "name", or "credits" >>> GPA
Type "A" for ascending, "D" for descending.D
The data has been written to GPA2_(GPA).py
>>>
Screenshot of output file “GPA2_(gpa).py after execution:
Want to see more full solutions like this?
Chapter 11 Solutions
Python Programming: An Introduction to Computer Science, 3rd Ed.
- create an array of 30 random numbers that range between 1and 100. And yet again, write a function that will receive a number from the userand determine if that number exists in the array or not. But this time, start bySORTING your input list. After a sort, the list in problem 1 is as follows:[2, 2, 3, 5, 12, 14, 14, 15, 23, 36, 39, 41, 44, 44, 45, 48,49, 50, 52, 52, 59, 71, 81, 82, 88, 89, 89, 93, 96, 97] Approach: Implement a method called findC(x, A, i, j), where x is the number we arelooking for in array A, the first index of the array is i and the last index is j. We wantto determine whether x exists in A anywhere between index i and index j. Your firstcall to this method will therefore look like this: findC(x, A, 0, A.length-1). In the body of your function, compare x with the item that is in the middle of thearray, as you did before. As before, call the middle of index of the array mid. But thistime, if x<=a[mid], recursively call your function to search ONLY the first half of…arrow_forwardThe function interleave_lists in python takes two parameters, L1 and L2, both lists. Notice that the lists may have different lengths. The function accumulates a new list by appending alternating items from L1 and L2 until one list has been exhausted. The remaining items from the other list are then appended to the end of the new list, and the new list is returned. For example, if L1 = ["hop", "skip", "jump", "rest"] and L2 = ["up", "down"], then the function would return the list: ["hop", "up", "skip", "down", "jump", "rest"]. HINT: Python has a built-in function min() which is helpful here. Initialize accumulator variable newlist to be an empty list Set min_length = min(len(L1), len(L2)), the smaller of the two list lengths Use a for loop to iterate k over range(min_length) to do the first part of this function's work. On each iteration, append to newlist the item from index k in L1, and then append the item from index k in L2 (two appends on each iteration). AFTER the loop…arrow_forwardQuestion in image Please explain the algorithm with the answer. Python programmingarrow_forward
- A user is going to enter numbers one at a time, entering 'q' when finished. Put the numbers in a list, sort it in numerical order, and print out the list. Then print out the middle element of the list. (If the list has an even number of elements, print the one just after the middle.) Remember that a list 1st of numbers can be sorted numerically by calling 1st.sort(), and can be printed with print(1st). You can assume that every entry is either a valid integer or is the letter 'q'. Examples: If the input is 4 3 6 7 3 q The output is [3, 3, 4, 6, 7] 4 If input is 4 3 6 7 3 2 q The output is [2, 3, 3, 4, 6, 7] 4arrow_forwardProblem2: A square matrix can be represented by a two-dimensionalarray with N rows and N columns. You may assume a maximum size of 50 rows and 50 columns. 1. Write an algorithm MakeEmpty(n), which sets the first n rows and n columns to zero. 2. Write an algorithm Add(M1, M2, M3), which adds two matrices M1 and M2 together to produce matrix M3. 3. Write an algorithm Subtract(M1, M2, M3), which subtracts matrix M2 from matrix M1 to produce matrix M3. 4. Write an algorithm Copy(M1, M2), which copies matrix M1 into matrix M2.arrow_forwardan algorithm ==> psudocode pleasearrow_forward
- Modify the code below according to what asking you to do. Please show your new modified code in a picture.arrow_forwardUsing c++ Create this program in this given instructions. Using a random number generator, create a list of 500 integers. Perform a benchmark analysis using some of the sorting algorithms from this chapter. What is the difference in execution speed? Implement the bubble sort using simultaneous assignment. A bubble sort can be modified to “bubble” in both directions. The first pass moves “up” the list, and the second pass moves “down.” This alternating pattern continues until no more passes are necessary. Implement this variation and describe under what circumstances it might be appropriate.arrow_forward2. The quick-sort algorithm presented in the book and covered in this course selects the first element in the list as the pivot. We can revise it by selecting the median among the first, middle, and last elements in the list. Implement your algorithm in java and upload your .java file.arrow_forward
- Write two methods, the first one to calculate and print the sum of even numbers in the above (MyList) array. The second is to calculate and print the count of odd elements in (MyList) array.arrow_forwardImagine you want to use insertion sort for sorting a deck of cards, where the suits are ordered [Clubs, Spades, Diamonds, Hearts]. Thus, all the clubs will be ordered [Ace, 1, 2.., Queen, King], then all the Spades, etc. Create the pseudocode for this problemarrow_forwardLet's add one last user-defined method to the program. This method, called FindName, is to return an integer representing the index (position) in the array where the name is found or 1 otherwise. The approach is to use a simple for loop to search the array and examine each location to see if the name stored at the location is what you are searching for. If it is, return the array index. If you search the entire array and do not find the name, return a -1. The method header will look like: public static int FindName(string name, string[] arrItems, int num) Add the following lines of code to Main after the call to Reverse Dump string locateName "Sue"; int found = if(found >= 0) FindName(locateName, dataArray, n); else Console.WriteLine("{0} was found in the array", locateName); Console.WriteLine("{0} does not exist in the array", locateName); Provide the details (the code) of your FindName method. Copy Copyarrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education