logo
18
Jan

Arithmetic Formatter.

This is an Arithmetic Formatter created in Python to take in different arithmetic equations and print them out in an easy to understand format.

The project below was written in Python and it is the backend component of an arithmetic formatter.

Code

#Arithmetic_arranger.py

import re

def arithmetic_arranger(problems, show_results = False):

### Different lines to print
first_number = list()
second_number = list()
operator = list()



# Limit of 5 problems solution
if len(problems) > 5:
return "Error: Too many problems."

#Breaking down the problem
for problem in problems:
problem = problem.split()
first_number.append(problem[0])
second_number.append(problem[2])
operator.append(problem[1])

# Looking for appropiate operators
for items in problems:
if "/" in items:
return "Error: Operator must be '+' or '-'."
if "*" in items:
return "Error: Operator must be '+' or '-'."

# Looking for letters
for problem in problems:
search = re.search("[A-Za-z]+", problem)
if search :
return "Error: Numbers must only contain digits."

# Checking out length - Max 4 digits
for operand in problems:
operand = operand.split()
if len(operand[0]) > 4 or len(operand[2]) > 4:
return "Error: Numbers cannot be more than four digits."

string_1 = []
string_2 = []
string_3 = []
string_4 = []



#Arranging line 1
for x in range (len(first_number)):
if len(first_number[x]) > len(second_number[x]):
string_1.append(" " + first_number[x])
else:
string_1.append(" " * (len(second_number[x]) - len(first_number[x]) + 2 ) + first_number[x])

#Arranging line 2
for x in range(len(second_number)):
if len(second_number[x]) > len(first_number[x]):
string_2.append( operator[x] + " " + second_number[x])

else:
string_2.append(operator[x] + " " * (len(first_number[x]) - len(second_number[x]) + 1) + second_number[x])

# Arranging line 3
for x in range(len(second_number)):
string_3.append("-" * (max(len(first_number[x]), len(second_number[x])) + 2))



if show_results == True:

for x in range(len(first_number)):
if operator[x] == "+":
sumx = str(int(first_number[x]) + int(second_number[x]))
else:
sumx = str(int(first_number[x]) - int(second_number[x]))

if len(sumx) > max(len(first_number[x]), len(second_number[x])):
string_4.append(" " + sumx )
else:
string_4.append(" " * (max(len(first_number[x]), len(second_number[x])) -len(sumx) + 2) + sumx)


arranged_problems = " ".join(string_1) + "\n" + " ".join(string_2) + "\n" + " ".join(string_3) + "\n" + " ".join(string_4)
return arranged_problems

else:
arranged_problems = " ".join(string_1) + "\n" + " ".join(string_2) + "\n" + " ".join(string_3)
return arranged_problems
logo

Welcome to Maven.

Sorry, our website doesn't support your web-browser.
Maybe something more modern would do the trick.

download chrome