Created
February 9, 2025 12:56
-
-
Save VRamazing/daa8f7e1c5030f1d8257969a745d08be to your computer and use it in GitHub Desktop.
Arithmetic Arranger
This file contains hidden or 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
def arithmetic_arranger(problems, show_answers=False): | |
n = len(problems) | |
ans_objects = [] | |
if n > 5: | |
return "Error: Too many problems." | |
for i, problem in enumerate(problems): | |
first, oper, second = problem.split(" ") | |
l1, l2 = len(first), len(second) | |
if l1 > 4 or l2 > 4: | |
return 'Error: Numbers cannot be more than four digits.' | |
firstInt, secondInt = 0, 0 | |
try: | |
firstInt = int(first) | |
secondInt = int(second) | |
except: | |
return 'Error: Numbers must only contain digits.' | |
if type(firstInt) != int or type(secondInt) != int: | |
pass | |
ans = 0 | |
if oper == "+": | |
ans = firstInt + secondInt | |
if oper == "-": | |
ans = firstInt - secondInt | |
if oper == "/" or oper == "*": | |
# print("Error: Operator must be '+' or '-'.") | |
return "Error: Operator must be '+' or '-'." | |
dash = "-" | |
if l1 > l2: | |
first = f" {first}" | |
diff = len(first) - l2 - 2 | |
second = f"{oper} {diff*' '}{second}" | |
elif l1 < l2: | |
second = f"{oper} {second}" | |
diff = len(second) - l1 | |
first = diff*" " + first | |
else: | |
second = f"{oper} {second}" | |
left_pad = len(second) - l1 | |
first = left_pad*" " + first | |
diff = abs(len(second) - l1) | |
max_op1_op2 = max(len(first), len(second)) | |
dash = "-"*max_op1_op2 | |
ans_string = str(ans) | |
if len(ans_string) < max_op1_op2: | |
ans_string = " "*(max_op1_op2 - len(ans_string)) + ans_string | |
ans_objects.append({ | |
"first": first, | |
"second": second, | |
"dash": dash, | |
"answer": ans_string | |
}) | |
ans_strings = [] | |
keys = ["first", "second", "dash", "answer"] | |
if not show_answers: | |
keys.pop() | |
for key in keys: | |
ans_string = "" | |
for i, item in enumerate(ans_objects): | |
if i != len(ans_objects) - 1: | |
ans_string+= f"{item[key]} " | |
else: | |
ans_string+= f"{item[key]}" | |
ans_strings.append(ans_string) | |
# print("3801 123\n- 2 + 49\n------ -----") | |
return "\n".join(ans_strings) | |
print(f'\n{arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"])}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment