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 “sort()” function,
- Create empty list.
- Create “for” loop,
- Assign the data from the file.
- Append the data to the new list using append() method.
- Call the function “sort()” to sort the data.
- Call the function “reverse()” to reverse the data.
- Return new list.
- Define the “main()” function,
- Assign the input file.
- Read the students record from the input file.
- Sort the data by calling “sort()” function.
- Assign the output file.
- Call the function “write_Students()”.
- Call the “main()” function.
- 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: “gpa_sort.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[1],
s[2], s[3]), file = out_file)
#Close the output file
out_file.close()
#Define the function
def sort(Students):
#Create empty list
new_Data = []
#Create for loop
for i in range(len(Students)):
#Assign tuple
x = (Students[i].gpa(), Students[i].get_Name(),
Students[i].get_Hours(), Students[i].getQ_Points())
#Append the data at the end of new list
new_Data.append(x)
#Call the function "sort()" to sort the data
new_Data.sort()
#Call the function "reverse()" to reverse the data
new_Data.reverse()
#Return new list
return new_Data
#Define main() function
def main():
#Print the string
print("This program sorts student grade information by GPA")
#Assign the file name
file_name = "gpa1.txt"
#Read the data from a file
data = read_Students(file_name)
#Sort the data
data = sort(data)
#Assign the file name
file_name = "gpa_(sort1).txt"
#Call the function
write_Students(data, file_name)
if __name__ == '__main__':
#Call the main() function
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 function 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
Output:
This program sorts student grade information by GPA
>>>
Screenshot of output file “gps_(sort1).txt after execution:
Want to see more full solutions like this?
Chapter 11 Solutions
Python Programming: An Introduction to Computer Science, 3rd Ed.
- The function swap_list_ends in python takes one parameter, L, which is a list. The function then swaps the first and last items in L and returns the object None. Notice that since L is mutable, the changes the function makes to L are visible back in the calling program. SPECIAL CASE: If the list 'L' is empty, then the function does nothing to L and returns None. For example: Test Result L = [1, 3, 9, 2] if not(swap_list_ends(L) is None): print("Error: function should return None") print(L) [2, 3, 9, 1] L = ['super', 'awesome', 'excellent'] if not(swap_list_ends(L) is None): print("Error: function should return None") print(L) ['excellent', 'awesome', 'super'] L = [True, False] if not(swap_list_ends(L) is None): print("Error: function should return None") print(L) [False, True]arrow_forwardWrite a java method to search for an element in an array using a linear search. Many list processing tasks, including searching, can be done recursively. The base case typically involves doing something with a limited number of elements in the list (say the first element), then the recursive step involves doing the task on the rest of the list. Think about how linear search can be viewed recursively; if you are looking for an item in a list starting at index i:o ¬If i exceeds the last index in the list, the item is not found (return -1).o ¬If the item is at list[i], return i.o ¬If the is not at list[i], do a linear search starting at index i+1arrow_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_forward
- Write a recursive function that finds the minimum value in an ArrayList. Your function signature should be public static int findMinimum(ArrayList<Integer>) One way to think of finding a minimum recursively is to think “the minimum number is either the last element in the ArrayList, or the minimum value in the rest of the ArrayList”. For example, if you have the ArrayList [1, 3, 2, 567, 23, 45, 9], the minimum value in this ArrayList is either 9 or the minimum value in [1, 3, 2, 567, 23, 45] ================================================ import java.util.*; public class RecursiveMin{public static void main(String[] args){Scanner input = new Scanner(System.in);ArrayList<Integer> numbers = new ArrayList<Integer>();while (true){System.out.println("Please enter numbers. Enter -1 to quit: ");int number = input.nextInt();if (number == -1){break;}else {numbers.add(number);}} int minimum = findMinimum(numbers);System.out.println("Minimum: " + minimum);}public static int…arrow_forwardWrite a recursive function that finds the minimum value in an ArrayList. Your function signature should be public static int findMinimum(ArrayList<Integer>) One way to think of finding a minimum recursively is to think “the minimum number is either the last element in the ArrayList, or the minimum value in the rest of the ArrayList”. For example, if you have the ArrayList [1, 3, 2, 567, 23, 45, 9], the minimum value in this ArrayList is either 9 or the minimum value in [1, 3, 2, 567, 23, 45] Hint:The trick is to remove the last element each time to make the ArrayList a little shorter. import java.util.*; public class RecursiveMin{public static void main(String[] args){Scanner input = new Scanner(System.in);ArrayList<Integer> numbers = new ArrayList<Integer>();while (true){System.out.println("Please enter numbers. Enter -1 to quit: ");int number = input.nextInt();if (number == -1){break;}else {numbers.add(number);}} int minimum =…arrow_forwardIn python, without using loopsarrow_forward
- The implementation of a queue in an array, as given in this chapter, uses the variable count to determine whether the queue is empty or full. You can also use the variable count to return the number of elements in the queue. On the other hand, class linkedQueueType does not use such a variable to keep track of the number of elements in the queue. Redefine the class linkedQueueType by adding the variable count to keep track of the number of elements in the queue. Modify the definitions of the functions addQueue and deleteQueue as necessary. Add the function queueCount to return the number of elements in the queue. Also, write a program to test various operations of the class you defined.arrow_forwardJava - Normalizingarrow_forwardPython’s list method sort includes the keyword argument reverse, whose defaultvalue is False. The programmer can override this value to sort a list in descendingorder. Modify the selectionSort function so that it allowsthe programmer to supply this additional argument to redirect the sort. selectionSort function: def selectionSort(lyst, profiler):i = 0 while i < len(lyst) - 1:minIndex = ij = i + 1 while j < len(lyst):profiler.comparison() # Countif lyst[j] < lyst[minIndex]:minIndex = jj += 1 if minIndex != i:swap(lyst, minIndex, i, profiler)i += 1 def swap(lyst, i, j, profiler):"""Exchanges the elements at positions i and j."""profiler.exchange() # Counttemp = lyst[i]lyst[i] = lyst[j]lyst[j] = temp Use this template in Python to modify the function above: def selection_sort(input_list, reverse):sorted_list = []#TODO: Your work here# Return sorted_listreturn sorted_listif __name__ == "__main__":my_list = [1, 2, 3, 4, 5]print(selection_sort(my_list, True)) # Correct Output: [5,…arrow_forward
- in java pls and thank you!arrow_forwardAssume that L is a list of Boolean values, True and False. Write a program in python with a function longestFalse(L) which returns a tuple (start, end) representing the start and end indices of the longest run of False values in L. If there is a tie, then return the first such run. For example, if L is False False True False False False False True True False False 0 1 2 3 4 5 6 7 8 9 10 then the function would return (3, 6), since the longest run of False is from 3 to 6.arrow_forwardPython please... Implement a function printIndex() that takes a list as a parameter, prompts the user to enter a whole number n, and prints the element in position Index[n]. If the list is empty ([]) or n is not a valid index into the list, the function will not print anything. Be careful to do the correct thing with negative indices. You should assume that the user will enter a whole number when prompted, and the function will crash if the user does not enter an integer. The function should not change the list passed as a parameter. Hint: Just because this involves a list does not mean that you need a loop to solve the problem. Think carefully about the right construct to use here. The following shows the function template, and several examples runs of the function (you must show all the examples with these values in your submission): Template def printIndex(lst): replace with your docstring newList = lst # ________________________ elementNum =…arrow_forward
- C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage Learning