Programing Assignment Sample
Q1:
Answer :Solution Approach:
To solve this problem efficiently, we break it down into smaller tasks and implement modular functions to handle different aspects of data processing. The program will:
Read the data from the file "grades.txt".
Parse and validate the data.
Compute required statistics.
Write the results to "report.txt".
Implementation Details:
Reading and Parsing the File:
The file "grades.txt" is opened and read line by line.
Each line is split into a name and a grade, ensuring that the grade is a valid numerical value.
Errors such as missing values or non-numeric grades are handled gracefully.
Computing Statistics:
The average grade is calculated as the sum of all grades divided by the number of students.
The highest and lowest grades are determined using the max()
and min()
functions.
The count of passing and failing students is maintained using simple conditional logic.
A dictionary is used to store the frequency distribution of grades in intervals of 10.
Writing to Output File:
The computed statistics are formatted neatly and written to "report.txt".
Code Implementation:
import os
def read_grades(filename):
grades = []
try:
with open(filename, 'r') as file:
for line in file:
try:
name, grade = line.strip().split(',')
grade = int(grade)
grades.append(grade)
except ValueError:
print(f"Skipping invalid line: {line.strip()}")
except FileNotFoundError:
print("Error: File not found.")
return []
return grades
def compute_statistics(grades):
if not grades:
return None
avg_grade = sum(grades) / len(grades)
max_grade = max(grades)
min_grade = min(grades)
pass_count = sum(1 for g in grades if g >= 50)
fail_count = len(grades) - pass_count
frequency_distribution = {i: 0 for i in range(0, 101, 10)}
for grade in grades:
for key in frequency_distribution.keys():
if key <= grade < key + 10:
frequency_distribution[key] += 1
break
return avg_grade, max_grade, min_grade, pass_count, fail_count, frequency_distribution
def write_report(filename, stats):
if stats is None:
with open(filename, 'w') as file:
file.write("No valid data available to generate report.\n")
return
avg, max_g, min_g, pass_c, fail_c, freq = stats
with open(filename, 'w') as file:
file.write(f"Class Average: {avg:.2f}\n")
file.write(f"Highest Grade: {max_g}\n")
file.write(f"Lowest Grade: {min_g}\n")
file.write(f"Passed Students: {pass_c}\n")
file.write(f"Failed Students: {fail_c}\n")
file.write("Grade Distribution:\n")
for key, value in sorted(freq.items()):
file.write(f"{key}-{key+9}: {value}\n")
# Main execution
filename = "grades.txt"
grades = read_grades(filename)
stats = compute_statistics(grades)
write_report("report.txt", stats)
Explanation of Code:
``: Reads and processes the file while handling errors.
``: Computes required statistics.
``: Writes the computed statistics to "report.txt".
Main execution block: Calls the functions in sequence.
Testing and Edge Cases Considered:
The file may not exist – handled using try-except
.
A line may have incorrect formatting – skips invalid lines with a warning.
The grade may not be a valid integer – uses exception handling.
Empty file scenario – provides a meaningful message in "report.txt".
Conclusion:
This approach ensures a robust, modular, and error-resistant solution. The use of functions enhances code reusability and readability, while error handling ensures reliability in real-world scenarios.