Question

In: Computer Science

In this problem, we'll write a Python module that defines two things publicly. A namedtuple called...

In this problem, we'll write a Python module that defines two things publicly.

  • A namedtuple called Student with two fields, scores and grade, intended to carry grade-related information about a student. (This will be part of the output of this problem.) So that we're all in agreement about what that will look like, here it is:
    Student = namedtuple('Student', ['scores', 'grade'])
    
  • A function named build_grade_report, which takes two parameters: a Path object describing the path to a file containing the "raw scores" for each student, and the ranges of total scores necessary to achieve each possible grade. (The details of both of these parameters are described in more detail below.)

The inputs

The first parameter to your function is the path to a file containing score information, but the interesting thing about it is the format of that information, which we'll need to agree on. What you'll expect is a text file in which each line of text represents one student's information. The first thing you'll see on each line is the student's UCInetID (i.e., an identifier that's unique for each student); after that will be a sequence of numbers that are separated by at least one space, which are that student's raw scores. Any line of text consisting only of spaces, or any line whose first non-space character is a # is to be ignored. Note that it is possible for a student to have no scores.

The second parameter to your function is a dictionary where the keys are letter grades and the values are tuples specifying the range of total scores that would lead to that letter grade. A tuple containing only one value would mean "The given score or anything higher," while a tuple containing two values would mean "Any score that's greater than or equal to the first of these, but is less than the second of these." For example, if the dictionary looked like this:

{'A': (600, ), 'B': (500, 600), 'C': (400, 500), 'D': (300, 400), 'F': (0, 300)}

then we'd expect any student scoring at least 600 points total would receive a grade of A, any student scoring at least 500 points but less than 600 would receive a B, and so on. Don't assume that the letter grades will always be A, B, C, D, and F, or even that they'll always be a single letter. It is expected that the ranges of scores will not overlap; if they do, your function can output any grade that matches (i.e., if 17 points is either a B or a C, you can return either grade for a student in that case).

The output

Your function will return a dictionary where the keys are the UCInetIDs of students who are listed in the file, and where the corresponding values are Student namedtuples with scores being a list of the student's scores (in the order listed on the corresponding line of the file) and grade being the student's grade.

Note that grades are calculated by determining the sum of all of a student's raw scores (i.e., there is no weighting scheme that makes one assignment worth more than another, which is different from the actual grading formula used in this course) and comparing it to the given grade ranges. If the total score is not in any of the given grade ranges, the student's score should be specified as the Python value None.

If the file cannot be opened or it cannot be read to completion, the function should raise an exception; it's not important what kind of exception it is, but the file should be closed in any circumstance in which it was opened successfully.

An example

Suppose that you had a file called scores.txt in the same directory as your problem3.py file, in which the following text appeared.

# Alex has work to do, but is improving
thornton 30 40 50 60 70 80 90
# Boo is perfect, as usual
boo 100 100 100 100 100 100 100
# Student that submitted no work; total score is 0
didnothing

Here's how your function should behave, given that file.

>>> grade_ranges = {'A': (600, ), 'B': (500, 600), 'C': (400, 500), 'D': (300, 400), 'F': (0, 300)}
>>> build_grade_report(Path('scores.txt'), grade_ranges)
{'thornton': Student(scores=[30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0], grade='C'),
 'boo': Student(scores=[100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0], grade='A'),
 'didnothing': Student(scores=[], grade='F')}

Solutions

Expert Solution

Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks. Please indent the code according to code screenshot

Code:

# -*- coding: utf-8 -*-
"""
Created on Sat Oct 31 10:37:33 2020

@author: Faraz
"""

from collections import namedtuple
from os import path

#creating named tuple
Student = namedtuple('Student', ['scores', 'grade'])


def build_grade_report(pathOfFile, ranges):
#checking if path is valid file name
if path.isfile(pathOfFile):
#opening file to read
file1 = open(pathOfFile, 'r')
#reading all lines
Lines = file1.readlines()
#output dictionary
output={}
#looping over each line
for line in Lines:
# Any line of text consisting only of spaces, or any line whose first non-space character is a # is to be ignored
if line.strip()!='' and ((not '#' in line) or line.index(' ')<line.index('#')):
#splitting by space
splitted=line.split(' ');
#getting id
UCInetID=splitted[0]
#for scores
score=[]
#for total score
totalScore=0
#if none criterion matches
gradeOfStud=None
#looping over each score
for i in range(1,len(splitted)):
score.append(float(splitted[i]))
#creating total score
totalScore=totalScore+float(splitted[i])
#looping to get grade
for grade in ranges:
#if tuple has one value only
if len(ranges[grade]) ==1 and totalScore>=ranges[grade][0]:
gradeOfStud=grade
break
else:
if(totalScore>=ranges[grade][0] and totalScore<ranges[grade][1]):
gradeOfStud=grade
break
#setting named tuple
S=Student(score,gradeOfStud)
#setting ouput for that student
output[UCInetID]=S
#returning ouput
return output

else:#exception for file
raise Exception("Please give valid file path")

#testing
grade_ranges = {'A': (600, ), 'B': (500, 600), 'C': (400, 500), 'D': (300, 400), 'F': (0, 300)}
print(build_grade_report('scores.txt',grade_ranges))

Code screenshot:

Output:


Related Solutions

Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file must satisfy the following. Define a function named rinsert. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall insert the element corresponding to the second parameter into the presumably sorted list from position 0 to one less...
In python please write the following code the problem. Write a function called play_round that simulates...
In python please write the following code the problem. Write a function called play_round that simulates two people drawing cards and comparing their values. High card wins. In the case of a tie, draw more cards. Repeat until someone wins the round. The function has two parameters: the name of player 1 and the name of player 2. It returns a string with format '<winning player name> wins!'. For instance, if the winning player is named Rocket, return 'Rocket wins!'.
Write a Class called Module with the following attributes: module code, module name, list of lecturers...
Write a Class called Module with the following attributes: module code, module name, list of lecturers for the module (some modules may have more than one lecturer – we only want to store their names), number of lecture hours, and module description. Create a parameterised (with parameters for all of the class attributes) and a non-parameterised constructor, and have the accessor and mutator methods for each attribute including a toString method. Write a class Student with the following attributes: student...
use python 1. Write a program that a. defines a list of countries that are members...
use python 1. Write a program that a. defines a list of countries that are members of BRICS (Brazil, Russia, India, China, Sri Lanka) b. Check whether a country is a member of BRICS or not Program run Enter the name of country: Pakistan Pakistan is not a member of BRICS Enter the name of country : India India is a member of BRICS 2. Write a program to create a list of numbers in the range of 1 to...
This is an intro to python question. #Write a function called search_for_string() that takes two #parameters,...
This is an intro to python question. #Write a function called search_for_string() that takes two #parameters, a list of strings, and a string. This function #should return a list of all the indices at which the #string is found within the list. # #You may assume that you do not need to search inside the #items in the list; for examples: # # search_for_string(["bob", "burgers", "tina", "bob"], "bob") # -> [0,3] # search_for_string(["bob", "burgers", "tina", "bob"], "bae") # -> []...
PYTHON: Write a script that imports the functions in the module below and uses all of...
PYTHON: Write a script that imports the functions in the module below and uses all of the functions. import math def _main():     print("#" * 28, "\n", "Testing...1, 2, 3...testing!\n", "#" * 28, "\n", sep="")     f = -200     print("{:.2f} F is {:.2f} C".format(f, f2c(f)))     f = 125     print("{:.2f} F is {:.2f} C".format(f, f2c(f)))     c = 0     print("{:.2f} C is {:.2f} F".format(c, c2f(c)))     c = -200     print("{:.2f} C is {:.2f} F".format(c, c2f(c))) def f2c(temp):     #Converts Fahrenheit tempature to Celcius     if temp <...
Write a Python program called arecongruent.py that determines whether two integers a and b are congruent...
Write a Python program called arecongruent.py that determines whether two integers a and b are congruent modulo n. Your code must work as follows: From the command prompt the user runs the program by typing python arecongruent.py and then your program interface prompts the user for the values of a, b, and n. The program outputs either True or False, and the values of a mod n and b mod n. Submit your Python source code arecongruent.py. NOTE: please include...
1. Write a Python program that performs the following: 2. Defines an array of integers from...
1. Write a Python program that performs the following: 2. Defines an array of integers from 1 to 10. The numbers should be filled automatically without the need for user inputs 3. Find the sum of the numbers that are divisible by 3 (i.e., when a number is divided by 3, the remainder is zero) 4. Swap the positions of the maximum and minimum elements in the array. First, you need to find the maximum element as shown in the...
6-Write a module in pseudocode called magicSix(), which accepts two integers and displays a message “Magic...
6-Write a module in pseudocode called magicSix(), which accepts two integers and displays a message “Magic 6!” if either of the two integers is a 6 or if their sum or difference is a 6. Otherwise, the program will display “Not a magic 6.” Note, you will need to determine the larger number when calculating the difference, to get a positive difference. You cannot use any built-in Python functions to do this. Type your pseudocode into your answer document. 7-...
/* Problem 1 * Write and run a java program that prints out two things you...
/* Problem 1 * Write and run a java program that prints out two things you have learned * so far in this class, and three things you hope to learn, all in different lines. */ You could write any two basic things in Java. /* Problem 2 * The formula for finding the area of a triangle is 1/2 (Base * height). * The formula for finding the perimeter of a rectangle is 2(length * width). * Write a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT