I am trying to write a basic s-expression calculator in Python using s-expression which can contains add or multiply or both or none or just an integar number.
I tried the following snippet:
def calc(expr):
print(expression[0])
if isinstance(expr, int):
return expr
elif expr[0] == '+':
return calc(expr[1]) + calc(expr[2])
elif expr[0] == '*':
return calc(expr[1]) * calc(expr[2])
else:
raise ValueError("Unknown operator: %s" % expr[0])
# Example usage
# expression = ('+', ('*', 3, 4), 5)
expression = (7)
result = calc(expression)
print(result)
When I tried to pass the expression ('+', ('*', 3, 4), 5)
, it gives the correct answer but when I just try to use number 7 or 7 inside tuple (7), it gives the above error. How to solve this?