Using python recursion to calculate the Parenthesis part not working

Joined
Feb 5, 2023
Messages
1
Reaction score
0
If I enter input with parentheses it resolves only what is inside the parentheses and not what is after or before, if I enter two expressions with parentheses it returns None. you can see it in the code.

def divide(a, b):
return a/b
def pow(a, b):
return a**b
def addA(a, b):
return a+b
def subA(a, b):
return a-b
def mul (a, b):
return a*b
operators = {
'+': addA,
'-': subA,
'*': mul,
'/': divide,
'^' : pow,


}

def calculate(s):
if s.isdigit():
return float(s)
elif '[' in s:
start = s.index('[')
end = s.rindex(']')
return calculate(s[start + 1:end])
for c in operators.keys():
left, operator, right = s.partition(c)
if operator in operators:
return operators[operator](calculate(left), calculate(right))

calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))

input: [2+2]+[2+2] output: None

input [2+3]*2 output 5
 
Joined
Sep 21, 2022
Messages
126
Reaction score
16
The first thing the recursive routine must do is find the TOP LEVEL operator in the string.

Convert the left into a number. (using recursion)

Convert the right into a number. (using recursion)

THEN do the operation, and return the number.

hint:
If the string starts with [ then the top level operator is after the ] that MATCHES the first [
 
Joined
Jan 30, 2023
Messages
107
Reaction score
13
If I enter input with parentheses it resolves only what is inside the parentheses and not what is after or before, if I enter two expressions with parentheses it returns None. you can see it in the code.

def divide(a, b):
return a/b
def pow(a, b):
return a**b
def addA(a, b):
return a+b
def subA(a, b):
return a-b
def mul (a, b):
return a*b
operators = {
'+': addA,
'-': subA,
'*': mul,
'/': divide,
'^' : pow,


}

def calculate(s):
if s.isdigit():
return float(s)
elif '[' in s:
start = s.index('[')
end = s.rindex(']')
return calculate(s[start + 1:end])
for c in operators.keys():
left, operator, right = s.partition(c)
if operator in operators:
return operators[operator](calculate(left), calculate(right))

calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))

input: [2+2]+[2+2] output: None

input [2+3]*2 output 5
The recursion to calculate the expression within the brackets does not seem to be working as expected. One possible issue could be that the code only checks for one set of brackets and does not handle multiple sets of brackets in the same expression. To handle such cases, you can modify the code to recursively calculate the expression within each set of brackets until there are no more brackets left in the expression. Another possible issue could be that the code is not handling cases where the expression within the brackets contains operators, which would cause the code to return None. To handle such cases, you can modify the code to perform the calculation within the brackets before returning the result.

Try this code base on your coding :

Code:
')
    return expression[start + 1:end]

def calculate(expression):
    if expression.isdigit():
        return float(expression)
    if '[' in expression:
        return calculate(extract_expression(expression))
    for operator in OPERATORS:
        left, operator, right = expression.partition(operator)
        if operator in OPERATORS:
            return OPERATORS[operator](calculate(left), calculate(right))

try:
    expression = input("Enter calculation: ")
except EOFError:
    expression = "[2+3]*2"

result = calculate(expression)
print("Answer:", result)

This code should handle expressions with multiple sets of brackets and perform the calculations within each set of brackets before returning the result.
 
Joined
Jan 30, 2023
Messages
107
Reaction score
13
The recursion to calculate the expression within the brackets does not seem to be working as expected. One possible issue could be that the code only checks for one set of brackets and does not handle multiple sets of brackets in the same expression. To handle such cases, you can modify the code to recursively calculate the expression within each set of brackets until there are no more brackets left in the expression. Another possible issue could be that the code is not handling cases where the expression within the brackets contains operators, which would cause the code to return None. To handle such cases, you can modify the code to perform the calculation within the brackets before returning the result.

Try this code base on your coding :

Code:
')
    return expression[start + 1:end]

def calculate(expression):
    if expression.isdigit():
        return float(expression)
    if '[' in expression:
        return calculate(extract_expression(expression))
    for operator in OPERATORS:
        left, operator, right = expression.partition(operator)
        if operator in OPERATORS:
            return OPERATORS[operator](calculate(left), calculate(right))

try:
    expression = input("Enter calculation: ")
except EOFError:
    expression = "[2+3]*2"

result = calculate(expression)
print("Answer:", result)

This code should handle expressions with multiple sets of brackets and perform the calculations within each set of brackets before returning the result.

Sorry i did a mistake .. EOF error ..

Here is the good coding :

Python:
def divide(a, b):
    return a / b

def pow(a, b):
    return a ** b

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

OPERATORS = {
    '+': add,
    '-': sub,
    '*': mul,
    '/': divide,
    '^': pow
}

def extract_expression(expression):
    start = expression.index('[')
    end = expression.rindex(']')
    return expression[start + 1:end]

def calculate(expression):
    if expression.isdigit():
        return float(expression)
    if '[' in expression:
        return calculate(extract_expression(expression))
    for operator in OPERATORS:
        left, operator, right = expression.partition(operator)
        if operator in OPERATORS:
            return OPERATORS[operator](calculate(left), calculate(right))

try:
    expression = input("Enter calculation: ")
except EOFError:
    expression = "[2+3]*2"

result = calculate(expression)
print("Answer:", result)
 
Joined
Sep 21, 2022
Messages
126
Reaction score
16
Kuncode is just plain wrong.

Here is some tested pseudocode (that looks a lot like BASIC).

assumptions:
No white space.
No unary -
Precedence rules do not apply, because brackets are always used.

Code:
FUNC PARSEMF(S)
REM parse string S
LOCAL char,I,level,P,top
level=0
top=0
FOR I=1 TO LEN(S)
 char=MID(S,I,1)
 IF char=="[" THEN
  level+=1
 ELSEIF char=="]" THEN
  level-=1
 ELSEIF char=="+" OR char=="-" OR char=="*" OR char=="/" THEN
  IF level==0 THEN top=I
 ENDIF
NEXT
IF top==0 THEN
 REM No top level operator, remove brackets and retry.
 P=PARSEMF(MID(S,2,LEN(S)-2))
ELSE
 P=[MID(S,1,top-1),MID(S,top,1),MID(S,top+1)]
 REM [every character left,operator,every character right]
ENDIF
PARSEMF=P
END

FUNC CALCMF(S)
REM calculate string S
LOCAL C,leftv,P,rightv
IF ISNUMBER(S) THEN
 C=VAL(S)
ELSE
 P=PARSEMF(S)
 leftv=CALCMF(P(0))
 rightv=CALCMF(P(2))
 IF P(1)=="+" THEN
  C=leftv+rightv
 ELSEIF P(1)=="-" THEN
  C=leftv-rightv
 ELSEIF P(1)=="*" THEN
  C=leftv*rightv
 ELSEIF P(1)=="/" THEN
  C=leftv/rightv
 ENDIF
ENDIF
CALCMF=C
END
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,813
Messages
2,569,696
Members
45,483
Latest member
TedDvb6626

Latest Threads

Top