Concept explainers
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.
- Check whether the type is “GPA” using “if”.
- If it is true, sort the data based on the “GPA”.
- Use “break” to exit.
- Check whether the type is “name” using “elif”.
- If it is true, sort the data based on the “name”.
- Use “break” to exit.
- Check whether the type is “credits” using “if”.
- If it is true, sort the data based on the “credits”.
- Use “break” to exit.
-
- Write the data into the output file.
- Check whether the type is “GPA” using “if”.
- Get the type of input to sort.
- 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
#Deine 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):
#Openthe input file for reading
in_file = open(file_name, 'r')
#Create an empty list
Students = []
#Create ffor 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" >>> '))
#Check whether the type is "GPA"
if x == 'GPA':
#Sort the data based on the gpa
data.sort(key=Student.gpa)
s = "_(GPA)"
#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)
s = "_(name)"
#Use break to exit
break
#Check whether the type is "credits"
elif x == 'credits':
#Sort the data based on the credit points
data.sort(key=Student.getQ_Points)
s = "_(credits)"
#Use break to exit
break
#Otherwise
else:
#Print the string
print("Please try again.")
#Assign the output file
file_name = "GPA2" + s + ".py"
#Writ the data into output file
write_Students(data, file_name)
#Print the output file
print("The data has been written to", file_name)
#Call 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 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)
#Check 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
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
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.
- In python please! I am strugglingarrow_forwardGiven a text file containing the availability of food items, write a program that reads the information from the text file and outputs the available food items. The program first reads the name of the text file from the user. The program then reads the text file, stores the information into four separate arrays, and outputs the available food items in the following format: name (category) -- description Assume the text file contains the category, name, description, and availability of at least one food item, separated by a tab character. Ex: If the input of the program is: food.txt and the contents of food.txt are: Sandwiches Ham sandwich Classic ham sandwich Available Sandwiches Chicken salad sandwich Chicken salad sandwich Not available Sandwiches Cheeseburger Classic cheeseburger Not available Salads Caesar salad Chunks of romaine heart lettuce dressed with lemon juice Available Salads Asian salad Mixed greens with ginger dressing, sprinkled with sesame Not available Drinks Water…arrow_forwardGiven a text file containing the availability of food items, write a program that reads the information from the text file and outputs the available food items. The program first reads the name of the text file from the user. The program then reads the text file, stores the information into four separate arrays, and outputs the available food items in the following format: name (category) -- description Assume the text file contains the category, name, description, and availability of at least one food item, separated by a tab character. Ex: If the input of the program is: food.txt and the contents of food.txt are: Sandwiches Ham sandwich Classic ham sandwich Available Sandwiches Chicken salad sandwich Chicken salad sandwich Not available Sandwiches Cheeseburger Classic cheeseburger Not available Salads Caesar salad Chunks of romaine heart lettuce dressed with lemon juice Available Salads Asian salad Mixed greens with ginger dressing, sprinkled with sesame Not available Drinks Water…arrow_forward
- Java languagearrow_forwardWrite a program that reads by asking the user the name of the file. After opening it, read it into the structure of array. The input file is in the format: firstName lastName age result (Contents of the input file) The Temp 0 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 Edward Newman 61 3 1 2 2 2 3 5 3 5 3 5 1 3 1 4 3 5 2 5 3 5 1 3 1 5 1 5 3 1 1 3 1 3 1 3 3 5 2 1 2 3 5 1 1 3 3 5 3 1 5 The program reads the result into the structure called TheResult. The constants and the structure to be used is given below: const int EXTROVERSION = 0; const int AGREEABLENESS = 1; const int CONSCIENTIOUSNESS = 2; const int NEUROTICISM = 3; const int OPEN_TO_EXPERIENCE = 4; const int NUM_QUESTIONS = 50; const int NUM_RESULT = 5; const int MAX_RESULT = 5; struct TheResult { string firstName; string lastName; int age; int answers[NUM_QUESTIONS]; // result double normalizedResult[NUM_RESULT]; }; The name of the input file is…arrow_forwardFor this programming exercise you will use the text file named “USPopulation.txt” that is located on Blackboard in the same location as these instructions. The file contains the midyear population of the United States, in thousands, during the years 1950 through 2000. The first line in the file contains the population for 1950, the second line contains the population for 1951, and so forth. Write a program that reads the contents of the file into an array. The program should display the following information: • The average annual change in population during the time period. • The year with the greatest increase in population during the time period. • The year with the smallest increase in population during the time period.arrow_forward
- This program asks the user to enter 4 names for a team, storing them in an array of Strings. Then the program asks for one of those names again, and a new name to substitute instead of that one. Finally, the program changes the array, making that substitution. This modified list of names is printed on the screen. You can see sample output at the end of this file.arrow_forwardProgramming Challenge #7: Word Frequency Count: Write a program that allows the user to specify a text file, opens the file, and prints a two-column table consisting of all the words in the file together with the number of times that each word appears. Words are space-delimited and case-sensitive. The table should list the words in alphabetical order.arrow_forwardJAVA PROGRAM Chapter 7. PC #16. 2D Array Operations with Additional Requirements Write a program that creates an ArrayList of ArrayList of Doubles. The program should ask the user to enter the filename from the keyboard and validate the file for existence. Once the file is verified, the program should load the two-dimensional ArrayList with test data from the file. Be careful, as some of the files will contain rows with different number of elements. The program should work regardless whether the input data is perfectly rectangular or ragged. The program should have the following methods: • main. Main entry point for the program. • getRowSubtotal. This method should accept a two-dimensional ArrayList as its first argument and an integer as its second argument. The second argument should be the index of the row in the ArrayList. The method should return the subtotal of the values in the specified row. • getColSubtotal. This method should accept a two-dimensional ArrayList as…arrow_forward
- JAVA PROGRAM Chapter 7. PC #16. 2D Array Operations with Additional Requirements Write a program that creates an ArrayList of ArrayList of Doubles. The program should ask the user to enter the filename from the keyboard and validate the file for existence. Once the file is verified, the program should load the two-dimensional ArrayList with test data from the file. Be careful, as some of the files will contain rows with different number of elements. The program should work regardless whether the input data is perfectly rectangular or ragged. The program should have the following methods: • main. Main entry point for the program. • getRowSubtotal. This method should accept a two-dimensional ArrayList as its first argument and an integer as its second argument. The second argument should be the index of the row in the ArrayList. The method should return the subtotal of the values in the specified row. • getColSubtotal. This method should accept a two-dimensional ArrayList as…arrow_forwardJAVA PROGRAM Chapter 7. PC #16. 2D Array Operations with Additional Requirements Write a program that creates an ArrayList of ArrayList of Doubles. The program should ask the user to enter the filename from the keyboard and validate the file for existence. Once the file is verified, the program should load the two-dimensional ArrayList with test data from the file. Be careful, as some of the files will contain rows with different number of elements. The program should work regardless whether the input data is perfectly rectangular or ragged. The program should have the following methods: • main. Main entry point for the program. • getRowSubtotal. This method should accept a two-dimensional ArrayList as its first argument and an integer as its second argument. The second argument should be the index of the row in the ArrayList. The method should return the subtotal of the values in the specified row. • getColSubtotal. This method should accept a two-dimensional ArrayList as…arrow_forwardJAVA PROGRAM Chapter 7. PC #16. 2D Array Operations with Additional Requirements Write a program that creates an ArrayList of ArrayList of Doubles. The program should ask the user to enter the filename from the keyboard and validate the file for existence. Once the file is verified, the program should load the two-dimensional ArrayList with test data from the file. Be careful, as some of the files will contain rows with different number of elements. The program should work regardless whether the input data is perfectly rectangular or ragged. The program should have the following methods: • main. Main entry point for the program. • getRowSubtotal. This method should accept a two-dimensional ArrayList as its first argument and an integer as its second argument. The second argument should be the index of the row in the ArrayList. The method should return the subtotal of the values in the specified row. • getColSubtotal. This method should accept a two-dimensional ArrayList as…arrow_forward
- Programming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENT