I was trying to write a basic calculator (only integers and +, * - operator) in python without importing any modules. Therefore I wrote a function that checks the syntax first and defined all illegal cases.
openingParenthesis = '('
closingParenthesis = ')'
def checkSyntax(self, expression):
tokens = expression.split()
counterOpeningParenthesis = 0
counterClosingParenthesis = 0
if tokens[0] in ['+', '*', ')'] or tokens[-1] in ['+', '*', '(']:
return False
for i in range(0, len(tokens)):
if tokens[i] == openingParenthesis:
counterOpeningParenthesis += 1
elif tokens[i] == closingParenthesis:
counterClosingParenthesis +=1
if counterOpeningParenthesis != counterClosingParenthesis:
return False
for i in range(0, len(tokens)-1):
if tokens[i] == '(' and tokens[i+1] == ')':
return False
elif tokens[i] == ('+' or '*') and tokens[i+1] == ('+' or '*'):
return False
elif tokens[i] == ')' and tokens[i+1] == '(':
return False
elif tokens[i] == ')' and tokens[i+1].isdigit():
return False
elif tokens[i] == ('+' or '*') and tokens[i+1] == ')':
return False
elif tokens[i].isdigit() and tokens[i+1].isdigit():
return False
elif tokens[i] == '(' and tokens[i+1] in ['+', '*']:
return False
else:
return True
When I was testing the syntax of the equation '( * ( ( -2 ) ) )' the following if-statement should have detect an error, but it didn't:
elif tokens[i] == '(' and tokens[i+1] == ('+' or '*'):
return False
If I change my if-statement to:
elif tokens[i] == '(' and tokens[i+1] in ['+', '*']:
return False
it detects the error. Anybody knows why?
Aucun commentaire:
Enregistrer un commentaire