test / algebra_solver.py
Mahdi Naser Moghadasi
Add interactive algebra solver module and fix worksheet parsing
f000309
Raw History Blame Contribute Delete
8.14 kB
"""
Algebra Problem Solver Module
Solves the types of algebra problems found in the science worksheet
"""
import math
from typing import Dict, List, Tuple, Union
class AlgebraSolver:
"""Solves various algebra problems from science worksheets"""
def __init__(self):
self.solutions = {}
def solve_speed_problem(self, distance: float, time: float) -> Dict[str, Union[float, str]]:
"""
Solve speed calculation problems: Speed = Distance / Time
Args:
distance: Distance in km
time: Time in hours
Returns:
Dictionary with solution details
"""
try:
speed = distance / time
return {
"problem_type": "speed",
"formula": "Speed = Distance / Time",
"calculation": f"{distance} / {time}",
"answer": round(speed, 2),
"unit": "km/h",
"solution": f"Speed = {distance} km / {time} h = {speed} km/h"
}
except ZeroDivisionError:
return {"error": "Time cannot be zero"}
def solve_volume_problem(self, mass: float, density: float) -> Dict[str, Union[float, str]]:
"""
Solve volume calculation problems: Volume = Mass / Density
Args:
mass: Mass in grams
density: Density in g/cm³
Returns:
Dictionary with solution details
"""
try:
volume = mass / density
return {
"problem_type": "volume",
"formula": "Volume = Mass / Density",
"calculation": f"{mass} / {density}",
"answer": round(volume, 2),
"unit": "cm³",
"solution": f"Volume = {mass} g / {density} g/cm³ = {volume} cm³"
}
except ZeroDivisionError:
return {"error": "Density cannot be zero"}
def solve_linear_equation(self, a: float, b: float, c: float) -> Dict[str, Union[float, str]]:
"""
Solve linear equations of the form: ax + b = c
Args:
a: Coefficient of x
b: Constant term
c: Right side constant
Returns:
Dictionary with solution details
"""
try:
if a == 0:
return {"error": "Coefficient 'a' cannot be zero"}
x = (c - b) / a
return {
"problem_type": "linear_equation",
"equation": f"{a}x + {b} = {c}",
"steps": [
f"{a}x + {b} = {c}",
f"{a}x = {c} - {b}",
f"{a}x = {c - b}",
f"x = {c - b} / {a}",
f"x = {x}"
],
"answer": round(x, 2),
"solution": f"x = {x}"
}
except Exception as e:
return {"error": str(e)}
def solve_quadratic_equation(self, h: float, coefficient: float = 4.9) -> Dict[str, Union[float, str]]:
"""
Solve quadratic equations of the form: h = coefficient * t²
Args:
h: Height value
coefficient: Coefficient (default 4.9 for gravity)
Returns:
Dictionary with solution details
"""
try:
if coefficient <= 0:
return {"error": "Coefficient must be positive"}
if h < 0:
return {"error": "Height cannot be negative"}
t_squared = h / coefficient
t = math.sqrt(t_squared)
return {
"problem_type": "quadratic_equation",
"equation": f"h = {coefficient} * t²",
"given": f"h = {h}",
"steps": [
f"{h} = {coefficient} * t²",
f"t² = {h} / {coefficient}",
f"t² = {t_squared}",
f"t = √{t_squared}",
f"t = {t}"
],
"answer": round(t, 2),
"unit": "s",
"solution": f"t = {t} s"
}
except Exception as e:
return {"error": str(e)}
def solve_worksheet_problems(self) -> Dict[str, Dict]:
"""
Solve all the problems from the worksheet example
Returns:
Dictionary with all solutions
"""
solutions = {}
# Practice Problems
solutions["speed_bike"] = self.solve_speed_problem(45, 1.5)
solutions["volume_density"] = self.solve_volume_problem(30, 5)
# Word Problems
solutions["chemistry_linear"] = self.solve_linear_equation(3, 5, 20)
solutions["physics_quadratic"] = self.solve_quadratic_equation(19.6, 4.9)
return solutions
def validate_student_answer(self, problem_type: str, student_answer: float,
problem_data: Dict) -> Dict[str, Union[bool, str, float]]:
"""
Validate student's answer against the correct solution
Args:
problem_type: Type of problem (speed, volume, linear, quadratic)
student_answer: Student's numerical answer
problem_data: Problem parameters
Returns:
Validation result
"""
try:
if problem_type == "speed":
correct = self.solve_speed_problem(problem_data["distance"], problem_data["time"])
elif problem_type == "volume":
correct = self.solve_volume_problem(problem_data["mass"], problem_data["density"])
elif problem_type == "linear":
correct = self.solve_linear_equation(problem_data["a"], problem_data["b"], problem_data["c"])
elif problem_type == "quadratic":
correct = self.solve_quadratic_equation(problem_data["h"], problem_data.get("coefficient", 4.9))
else:
return {"error": "Unknown problem type"}
if "error" in correct:
return correct
tolerance = 0.01 # Allow small rounding differences
is_correct = abs(student_answer - correct["answer"]) < tolerance
return {
"is_correct": is_correct,
"student_answer": student_answer,
"correct_answer": correct["answer"],
"difference": abs(student_answer - correct["answer"]),
"feedback": "Correct!" if is_correct else f"Try again. The correct answer is {correct['answer']}"
}
except Exception as e:
return {"error": str(e)}
def test_algebra_solver():
"""Test the algebra solver with worksheet problems"""
solver = AlgebraSolver()
print("🧮 Testing Algebra Solver Module")
print("=" * 50)
# Test all worksheet problems
solutions = solver.solve_worksheet_problems()
for problem_name, solution in solutions.items():
print(f"\n📝 {problem_name.replace('_', ' ').title()}:")
if "error" in solution:
print(f"❌ Error: {solution['error']}")
else:
print(f"✅ {solution['solution']}")
if "steps" in solution:
print(" Steps:")
for step in solution["steps"]:
print(f" • {step}")
# Test validation
print(f"\n🔍 Testing Answer Validation:")
# Test correct answer
validation = solver.validate_student_answer("speed", 30.0, {"distance": 45, "time": 1.5})
print(f"Student answer 30.0 for speed problem: {validation}")
# Test incorrect answer
validation = solver.validate_student_answer("speed", 25.0, {"distance": 45, "time": 1.5})
print(f"Student answer 25.0 for speed problem: {validation}")
return solutions
if __name__ == "__main__":
test_algebra_solver()