Home > Net >  Parenthesis Operation in PEMDAS Python
Parenthesis Operation in PEMDAS Python

Time:11-15

This function works as the Parenthesis operation in PEMDAS. I already have the PEMDAS Function working okay for the EMDAS operations, and this is the only operation I need to correct for my PEMDAS function to work okay.

It works for nested cases (1 (1 1)) as we well as multiple, separated cases (1 1) (1 1). However, it doesn't work with the combination of the two (1 (1 1)) (1 1). How can I modify the code so that it can take the last case into account? Note: We're not allowed to use regex.

def paren(equation):
    for i in range(len(equation)):
        if equation[i] == "(":
            for j in range(i   1, len(equation)):
                if equation[j] == ')':
                    return equation[i   1:j]
                elif equation[j] == '(':
                    for x in range(len(equation) - 1, -1, -1):
                        if equation[x] == ')':
                            return equation[i   1:x]
                else:
                    continue

SAMPLES:

  • Input1: (1 (1 1))

  • Output1: 1 (1 1)

  • Input2: (1 1) (2 2)

  • Output2: 1 1 (outputted the eq from the first bracket so that it can be solved first)

  • Input3: (1 (1 1)) (1 1)

  • EXPECTED Output3: 1 (1 1)

  • Output3: 1 (1 1)) (1 1

CodePudding user response:

This works for your test case. I count the numbers of open parentheses to find where to close the first equation.

def paren2(equation):
    equation = equation.replace(' ', '')
    open_parentheses_index_ = -1
    open_parentheses_count_ = 0
    close_parentheses_count_ = 0
    for i in range(len(equation)):
        if equation[i] == "(":
            if open_parentheses_index_ == -1:
                open_parentheses_index_ = i 
            open_parentheses_count_  = 1
        elif equation[i] == ")":
            close_parentheses_count_  = 1
            if open_parentheses_count_ == close_parentheses_count_:
                return equation[open_parentheses_index_ 1 : i] 
  • Related