Created
September 4, 2020 18:46
-
-
Save neenjaw/7c85a46f5c48441d167b1f08cd138d0f to your computer and use it in GitHub Desktop.
Arithmetic Arranger
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
from problem import ArithmeticProblem | |
def arithmetic_arranger(problems, show_answer=False): | |
try: | |
if len(problems) > 5: | |
raise ValueError("Too many problems.") | |
def convert_problem(s): | |
return str(ArithmeticProblem(s, show_answer)).splitlines() | |
equations = map(convert_problem, problems) | |
zipped_lines = zip(*equations) | |
arranged = "\n".join([" ".join(line) for line in zipped_lines]) | |
return arranged | |
except ValueError as err: | |
return f"Error: {err}" |
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
# This entrypoint file to be used in development. Start by reading README.md | |
from arithmetic_arranger import arithmetic_arranger | |
from unittest import main | |
print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])) | |
# Run unit tests automatically | |
main(module='test_module', exit=False) |
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
class ArithmeticProblem: | |
VALID_OPERATIONS = ('+', '-') | |
def __init__(self, problem, show_answer=False): | |
value_a, operation, value_b = problem.split() | |
if operation not in ArithmeticProblem.VALID_OPERATIONS: | |
raise ValueError("Operator must be '+' or '-'.") | |
self.operation = operation | |
for v in [value_a, value_b]: | |
if not v.isnumeric(): | |
raise ValueError("Numbers must only contain digits.") | |
if len(v) > 4: | |
raise ValueError("Numbers cannot be more than four digits.") | |
self.a = int(value_a) | |
self.b = int(value_b) | |
self.answer = self.a + self.b if self.operation == "+" else self.a - self.b | |
self.show_answer=show_answer | |
def __str__(self): | |
a_length = len(str(self.a)) | |
b_length = len(str(self.b)) | |
longest = a_length if a_length >= b_length else b_length | |
s = ( | |
f" {(self.a):>{longest}}\n" | |
f"{self.operation} {self.b:>{longest}}\n" | |
f"--{'-' * longest}" | |
) | |
if self.show_answer: | |
s += f"\n{self.answer:>{longest + 2}}" | |
return s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment