-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath_problem.py
More file actions
43 lines (32 loc) · 1.24 KB
/
Copy pathmath_problem.py
File metadata and controls
43 lines (32 loc) · 1.24 KB
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
import random
from dataclasses import dataclass
@dataclass(frozen=True)
class MathProblem:
text: str
answer: int
def _generate_division_problem(max_operand):
# Avoid trivial division like x / 1 or x / x = 1.
while True:
answer = random.randint(2, max_operand // 2)
max_divisor = max_operand // answer
if max_divisor < 2:
continue
right = random.randint(2, max_divisor)
left = answer * right
return MathProblem(f"{left} / {right}", answer)
def generate_problem(level_config):
operation = random.choice(tuple(level_config.max_operands))
max_operand = level_config.max_operands[operation]
if operation == "+":
left = random.randint(0, max_operand)
right = random.randint(0, max_operand)
return MathProblem(f"{left} + {right}", left + right)
if operation == "-":
left = random.randint(0, max_operand)
right = random.randint(0, left)
return MathProblem(f"{left} - {right}", left - right)
if operation == "*":
left = random.randint(0, max_operand)
right = random.randint(0, max_operand)
return MathProblem(f"{left} * {right}", left * right)
return _generate_division_problem(max_operand)