Я работаю над калькулятором, который будет принимать данные от пользователя. Он должен решать такие выражения, как:
1+38*(!2)-5%37
Я работал над сложением и вычитанием, но столкнулся с проблемой.
У меня есть цикл, который ищет символы «+» или «-». Для «+» это работает, но для «-» всякий раз, когда я решаю выражение вроде
1-38
Это приводит меня к бесконечному циклу, так как результат этого выражения
-37
и цикл продолжает распознавать символ "-" как вычитание, но как минус 37.
Как решить эту проблему?
def symbols_exist(exp, symbols_list):
""" Gets an expression string and a symbols list and returns true if any symbol
exists in the expression, else returns false. """
for s in symbols_list:
if s in exp:
return True
return False
def BinaryOperation(exp, idx):
""" Gets an expression and an index of an operator and returns a tuple with (first_value, operator, second_value). """
first_value = 0
second_value = 0
#Get first value
idx2 = idx -1
while (idx2 > 0) and (exp[idx2] in string.digits):
idx2 -=1
first_value = exp[idx2:idx]
#Get second value
idx2 = idx +1
while (idx2 < len(exp)) and (exp[idx2] in string.digits):
idx2 += 1
second_value = exp[idx+1:idx2]
return (first_value, exp[idx], second_value)
def solve(exp):
if not symbols_exist(exp, all_symbols):
return exp
idx = 0
while idx < len(exp):
if exp[idx] in string.digits:
#Digit
idx +=1
elif exp[idx] in ("+", "-"):
#Addition and Subtraction
sub_exp = BinaryOperation(exp, idx)
if sub_exp[1] == "+":
value = int(sub_exp[0]) + int(sub_exp[2])
else:
value = int(sub_exp[0]) - int(sub_exp[2])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
print exp
return solve(exp)
symbols_exist
так, чтобы она удаляла все начальные-
перед поиском символа? (например,if exp[0] == '-': exp = exp[1:]
) - person Stuart   schedule 03.12.2012