Spaces:
Sleeping
Sleeping
File size: 8,141 Bytes
f000309 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | """
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()
|