Elementary Arithmetic Exercise Generation and Grading System

PSP Performance Analysis

PSP2.1 Personal Software Process Stages Estimated Time (minutes) Actual Time (minutes)
Planning Planning 60 50
· Estimate · Time estimation for task 60 50
Development Development 635 665
· Analysis · Requirements analysis (including learning new technologies) 60 50
· Design Spec · Design documentation generation 30 30
· Design Review · Design review 25 35
· Coding Standard · Code standards establishment 20 30
· Design · Detailed design 60 50
· Coding · Implementation coding 300 300
· Code Review · Code review 20 20
· Test · Testing (self-testing, code modification, submissoin) 120 150
Reporting Reporting 90 90
· Test Report · Testing report 40 50
· Size Measurement · Workload calculation 20 20
· Postmortem & Process Improvement Plan · Post-project summary and improvement plan 30 20
· Total 785 805

System Architecture Design

The codebase follows a modular design with these core components:

  1. Command Line Argument Parser - Handles command line parameter parsing for program usage
  2. Number Generator - Generates random integers and proper fractions
  3. Expression Generator - Creates random arithmetic expressions
  4. File Generator - Produces exercise and answer files
  5. Grading Module - Evaluates user-provided exercise and answer files

Core Implementation Details

Command Line Argument Handler

def process_arguments():
    arg_parser = argparse.ArgumentParser(description="Elementary arithmetic exercise generator")
    arg_parser.add_argument("-n", type=int, help="Number of exercises to generate")
    arg_parser.add_argument("-r", type=int, help="Value range for numbers and fractions")
    arg_parser.add_argument("-e", type=str, help="Exercise file path")
    arg_parser.add_argument("-a", type=str, help="Answer file path")
    parsed_args = arg_parser.parse_args()

    # Validate required parameters
    if parsed_args.n and not parsed_args.r:
        print("Value range parameter required!")
        sys.exit(1)

    # Parameter validation
    if parsed_args.n and parsed_args.n <= 0:
        print("Exercise count must be positive!")
        sys.exit(1)
    if parsed_args.r and parsed_args.r <= 0:
        print("Value range must be positive!")
        sys.exit(1)
    
    return parsed_args

Arithmetic Expression Builder

def create_arithmetic_expression(max_value):
    operations = ['+', '-', '*', '/']
    
    # Parenthesis tracking
    open_parenthesis = False
    close_parenthesis = False

    # Initialize expression with first number
    math_expression = str(generate_random_number(max_value))

    # Randomly add opening parenthesis
    if random.choice([True, False]):
        math_expression = "(" + math_expression
        open_parenthesis = True

    # Generate remaining operations and numbers
    for _ in range(random.randint(1, 3)):
        operator = random.choice(operations)
        operand = generate_random_number(max_value)

        # Parenthesis placement logic
        if not open_parenthesis and random.choice([True, False]):
            math_expression += f" {operator} ({operand}"
            open_parenthesis = True
        elif open_parenthesis and not close_parenthesis:
            math_expression += f" {operator} {operand})"
            close_parenthesis = True
            open_parenthesis = False
        else:
            math_expression += f" {operator} {operand}"

    # Close any remaining open parenthesis
    if open_parenthesis and not close_parenthesis:
        math_expression += ")"

    # Clean up unnecessary parentheses
    if math_expression[0] == '(' and math_expression[-1] == ')':
        math_expression = math_expression[1:-1]
    math_expression = re.sub(r'\((\d+|\d+/\d+)\)', r'\1', math_expression)
    
    return math_expression

Automated Grading System

def evaluate_exercises(exercise_path, answer_path):
    with open(exercise_path, "r") as ex_file, open(answer_path, "r") as ans_file:
        exercise_lines = ex_file.readlines()
        answer_lines = ans_file.readlines()

    correct_answers = []
    incorrect_answers = []

    for index, (exercise, answer) in enumerate(zip(exercise_lines, answer_lines), 1):
        # Extract user and correct answers
        user_solution = re.search(r'=(.*)', exercise).group(1).strip()
        correct_solution = re.search(r'\d+\.(.*)', answer).group(1).strip()

        if user_solution == correct_solution:
            correct_answers.append(index)
        else:
            incorrect_answers.append(index)

    # Generate grading report
    with open("GradeReport.txt", "w") as report_file:
        report_file.write(f"Correct: {len(correct_answers)} ({', '.join(map(str, correct_answers))})\n")
        report_file.write(f"Incorrect: {len(incorrect_answers)} ({', '.join(map(str, incorrect_answers))})\n")

Test Scenarios and Validation

Test Case 1: Basic Generation

python arithmetic_generator.py -n 5 -r 10

Expected: 5 arithmetic problems with numbers 1-10, proper formatting in Exercises.txt and Answers.txt

Test Case 2: Fraction Operations

python arithmetic_generator.py -n 3 -r 3

Expected: 3 problems with fraction operations, answers in a/b or mixed number format

Test Case 3: Large Number Range

python arithmetic_generator.py -n 10 -r 100

Expected: 10 problems with numbers 1-100, including fractions and large number operations

Test Case 4: Division by Zero Prevention

python arithmetic_generator.py -n 5 -r 5

Expected: No division by zero operations in generated problems

Test Case 5: Duplicate Prevention

python arithmetic_generator.py -n 10 -r 5

Expected: 10 unique problems without repetition

Test Case 6: File Path Error Handling

python arithmetic_generator.py -e Exercises.txt -a InvalidPath.txt

Expected: Appropriate error message for missing file

Test Case 7: Answer Verification

python arithmetic_generator.py -e Exercises.txt -a Answers.txt

Expected: Correct generation of GradeReport.txt with accurate scoring

Test Case 8: Operator Precedence and Parentheses

python arithmetic_generator.py -n 5 -r 10

Expected: Proper operator precedence handling and meaningful parentheses usage

Test Case 9: Mixed Number Formatting

python arithmetic_generator.py -n 5 -r 7

Expected: Proper formatting of mixed numbers as integer'numerator/denominator

Test Case 10: Small Range Validation

python arithmetic_generator.py -n 1 -r 2

Expected: Single problem with simple arithmetic operations

Validation Criteria

  1. Boundary Value Analysis: Program handles various range and count combinations
  2. Division by Zero Prevention: System avoids invalid division operations
  3. Fraction Handling: Proper generation and formatting of fractions
  4. Parentheses Optimizaton: Removal of unnecessary parentheses
  5. Answer Accuracy: Manual verification of calculation correctness
  6. Duplicate Prevention: Ensures unique problem generation
  7. Format Consistency: Proper formatting of all answer types

Tags: python arithmetic education automation testing

Posted on Fri, 30 Oct 2026 16:04:43 +0000 by falcons