Created
October 23, 2022 01:51
-
-
Save forrcaho/ec37aaf7d9ccf3dc251af8d8b852abd1 to your computer and use it in GitHub Desktop.
Quiz for practicing factorization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import re | |
from typing import Tuple | |
class FactorizationProblem: | |
"""Generates a factorization problem""" | |
def coinflip() -> bool: | |
return (random.randrange(2) == 0) | |
factors = [(1, 1), (2, 1), (2, 2), (4, 1), (3, 1), (3, 2), (6, 1), (3, 3), (9, 1), | |
(4, 2), (8, 1), (4, 3), (6, 2), (12, 1), (4, 4), (8, 2), (16, 1), | |
(5, 1), (5, 2), (10, 1), (5, 3), (15, 1), (5, 4), (10, 2), (20, 1), (5, 5), (25, 1)] | |
def __init__(self): | |
(self.a, self.b) = random.choice(FactorizationProblem.factors) | |
if FactorizationProblem.coinflip(): | |
self.a = -self.a | |
if FactorizationProblem.coinflip(): | |
self.b = -self.b | |
def get_problem_string(self): | |
problem = "x^2 " | |
if (self.a + self.b) < 0: | |
if (self.a + self.b) == -1: | |
problem += "- x " | |
else: | |
problem += f"- {-self.a - self.b}x " | |
else: | |
if (self.a + self.b) == 1: | |
problem += "+ x " | |
else: | |
problem += f"+ {self.a + self.b}x " | |
if self.a * self.b < 0: | |
problem += f"- {-self.a * self.b}" | |
else: | |
problem += f"+ {self.a * self.b}" | |
return problem | |
def check_answer(self, factors: Tuple[int, ...]) -> bool: | |
if factors == (self.a, self.b) or factors == (self.b, self.a): | |
return True | |
return False | |
def extract_numbers(in_str: str) -> Tuple[int, ...]: | |
num_strs = re.findall(r'-?\d+', in_str) | |
return tuple(map(int, num_strs)) | |
def main(): | |
keep_asking = True | |
correct_count = 0 | |
wrong_count = 0 | |
while keep_asking: | |
problem = FactorizationProblem() | |
print(problem.get_problem_string()) | |
answer_str = input("What are the factors? ") | |
factors = extract_numbers(answer_str) | |
if problem.check_answer(factors): | |
correct_count += 1 | |
print("Right") | |
else: | |
wrong_count += 1 | |
print("Wrong") | |
print( | |
f"\n{correct_count} right answers {wrong_count} wrong answers\n") | |
response = input("Hit enter for next problem, any text to quit: ") | |
if len(response) > 0: | |
keep_asking = False | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment