Я пытаюсь сделать простой калькулятор с вводом всего уравнения, но загвоздка в том, что я не могу использовать eval() или что-то подобное. Я что-то написал, и это, вероятно, не лучшее решение, но это то, что я придумал. Проблема в том, что если я ввожу «2 + 5» в качестве входных данных, окончательный вывод будет ошибкой, говорящей, что он не может int() «2+»
Вот код:
print("Calculator 2.0")
while True:
equation = input(": ")
# Remove spaces
calculate = equation.replace(" ", "")
# Converting to list
calculate = list(calculate)
# Merging numbers next to one another
i = 0
startingIndex = -1
numCounter = 1
num = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
while i < len(calculate):
if calculate[i] in num:
if startingIndex == -1:
startingIndex = i
numCounter += 1
else:
calculate[startingIndex : numCounter] = [''.join(calculate[startingIndex : numCounter])]
startingIndex = -1
numCounter = 1
i += 1
solved = False
answer = 0
while solved == False:
# Check for multiplication and division
i = 0
while i < len(calculate):
divideIndex = -1
multiplyIndex = -1
j = 0
while j < len(calculate):
if calculate[j] == "*":
multiplyIndex = j
elif calculate[j] == "/":
divideIndex = j
j += 1
# Solve the multiplication and division
if multiplyIndex != -1:
calculate[multiplyIndex] = str(int(calculate[multiplyIndex - 1]) * int(calculate[multiplyIndex + 1]))
del calculate[multiplyIndex - 1]
del calculate[multiplyIndex + 1]
if divideIndex != -1:
calculate[divideIndex] = str(int(calculate[divideIndex - 1] / int(calculate[divideIndex + 1])))
del calculate[divideIndex - 1]
del calculate[divideIndex + 1]
i += 1
# Check for addition and subtraction
i = 0
while i < len(calculate):
sumIndex = -1
subtractIndex = -1
j = 0
while j < len(calculate):
if calculate[j] == "+":
sumIndex = j
elif calculate[j] == "-":
subtractIndex = j
j += 1
# Solve the addition and subtraction
if sumIndex != -1:
calculate[sumIndex] = str(int(calculate[sumIndex - 1]) + int(calculate[sumIndex + 1]))
del calculate[sumIndex - 1]
del calculate[sumIndex + 1]
if subtractIndex != -1:
calculate[subtractIndex] = str(int(calculate[subtractIndex - 1]) - int(calculate[subtractIndex + 1]))
del calculate[subtractIndex - 1]
del calculate[subtractIndex + 1]
i += 1
answer = int(calculate[0])
print(answer)
solved = True
да, но в какой части я пытался что-то изменить, но результат не изменился
Не беспокойся, я тебя понял
Посмотрите на алгоритм Shunting-yard, который преобразует инфикс в нотацию RPN. Затем добавьте его вывод в калькулятор обратной польской записи.
@Mikhail да, но дело в том, что я должен делать все с нуля, поэтому никаких библиотек, модулей и т. д.
Попробуйте это:
def Numbers(var):
return (
var == "0"
or var == "1"
or var == "2"
or var == "3"
or var == "4"
or var == "5"
or var == "6"
or var == "7"
or var == "8"
or var == "9"
)
def Test4Num(varstr):
n = 0
var = ""
try:
while Numbers(varstr[n]):
var += varstr[n]
n += 1
except:
pass
return (int(var), n)
def operation(string, num1, num2):
if string == "+":
return num1 + num2
if string == "-":
return num1 - num2
if string == "*":
return num1 * num2
if string == "/":
return num1 / num2
if string == "^":
return num1**num2
def operator(operato):
return (
operato == "+"
or operato == "-"
or operato == "*"
or operato == "/"
or operato == "^"
)
def eval_math_expr(expr):
negate = False
expr = expr.replace(" ", "")
while True:
try:
if expr[0] == "-": # for negative numbers
negate = True # because here the numbers are string format
expr = expr[1:]
number1 = Test4Num(expr)[0]
if negate == True:
number1 = -number1
negate = False
end_number1 = Test4Num(expr)[1]
expr = expr[end_number1:]
if expr == "":
return number1
op = expr[0]
expr = expr[1:]
number2 = Test4Num(expr)[0]
end_number2 = Test4Num(expr)[1]
result = operation(op, number1, number2)
number1 = result
expr = str(number1) + expr[end_number2:]
except Exception as e:
print(e)
break
return number1
if __name__ == "__main__":
expr = input("Enter your expression:")
print(expr + "=")
print(eval_math_expr(expr))
Ваше форматирование немного не так? Вы можете отредактировать это, чтобы сделать его более понятным...