Skip to content

Latest commit

 

History

History
113 lines (93 loc) · 3.65 KB

_224. Basic Calculator.md

File metadata and controls

113 lines (93 loc) · 3.65 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 10, 2024

Last updated : July 01, 2024


Related Topics : Math, String, Stack, Recursion

Acceptance Rate : 44.06 %


Solutions

Python

# Terrible runtime but it passed lol
# Will redo with a stack later

# I aint proud of this code lol in hindsight I can see how much
# better it would be using the stack method

class Solution:
    def calculate(self, s: str) -> int:
        s = s.replace(' ', '') # strip unnecessary info
        if s == '' :
            return 0
        if s == '-' :
            return -1

        # brackets first
        if '(' in s :
            leftIndx = s.find('(')
            rightIndx = leftIndx
            counter = 1
            while counter > 0 :
                rightIndx += 1
                if s[rightIndx] == '(' :
                    counter += 1
                elif s[rightIndx] == ')' :
                    counter -= 1

            retVal = 0
            if ('-' == s[leftIndx - 1]) : # negative before the bracket / subtraction
                retVal = self.calculate(s[0:leftIndx - 1]) + \
                            -1 * self.calculate(s[leftIndx + 1:rightIndx]) + \
                            self.calculate(s[rightIndx + 1:])
            else :
                retVal = self.calculate(s[0:leftIndx]) + \
                            self.calculate(s[leftIndx + 1:rightIndx]) + \
                            self.calculate(s[rightIndx + 1:])

            # print(s[0:leftIndx], s[leftIndx + 1:rightIndx], s[rightIndx + 1:])
            return retVal

        # is already just a number currently
        operators = set(list('+-*/'))
        if not any(op in s for op in operators) :
            return int(s)
        
        # operator present
        # mult and div first from left to right
        # NOTE: no brackets are present so we can just operate left to right
        expression = []
        currentNum = []
        addMin = set(list('+-'))
        for c in s :
            if c in addMin :
                expression.append(''.join(currentNum))
                currentNum = []
                if c == '-' : # treat subtractions like adding a negative number
                    currentNum.append('-')
            else : # numeric or */
                currentNum.append(c)

        expression.append(''.join(currentNum)) # final value in the sequence of added vals

        # sum all the values calculated
        output = 0
        for exp in expression :
            if exp == '' :
                continue
            if '*' in exp or '/' in exp :
                vals = list(reversed(re.split('[*/]', exp)))
                operators = list(reversed(re.findall('[*/]', exp)))
                while operators :
                    if operators.pop() == '*' :
                        vals.append(int(vals.pop()) * int(vals.pop()))
                    else :
                        a, b = int(vals.pop()), int(vals.pop())
                        print(a, b)
                        if (a >= 0) == (b >= 0) :
                            temp = a // b
                        else :
                            temp = -1 * (abs(a) // abs(b))
                        vals.append(temp)
                output += vals.pop()
            else :
                output += int(exp)
        return output