Dec-16-2021, 01:40 PM
(This post was last modified: Dec-16-2021, 01:40 PM by muddybucket.)
Hi, I am tasked to make a recursive function which evaluates the expression starting from the given position. Return the value and the first position after the read sub-expression. If the string starting at the given expression is not an arithmetic expression, return None. To avoid divisions by zero we do not allow division in arithmetic expressions.
But it outputs this error:
- If a is a number, then evaluate(a) is that number.
- If a and b are arithmetic expressions, then evaluate((a+b)) = evaluate(a)+evaluate(b), evaluate((a-b)) = evaluate(a)-evaluate(b), and evaluate((a*b)) = evaluate(a)*evaluate(b).
def read_positive_integer(text, position): text_mod = text[position:] if not (text[position]).isdigit(): return None try: return (int(text_mod), len(text_mod) + position ) except: return read_positive_integer(text[:-1], position) def evaluate(expression, position): r = read_positive_integer(expression, position) if r != None: return r else: if expression[position] == "(": a,pos = evaluate(expression, position+1) operator = expression[pos] b,pos = evaluate(expression, pos+1) op_dict = {"+":a+b, "-":a-b, "*":a*b} if expression[pos] == ")": return op_dict[operator]I have tried giving it the following input:
evaluate("((1-1)+(2*1))", 0)
But it outputs this error:
Error:cannot unpack non-iterable int object
PD: The function read_positive_integer has no flaws and it works as it should (it got accepted by the auto-corrector)