Basic Calculator (II)¶

The algorithm works in two steps, split and compute (we need to respect operations priorities):¶
1) Split the expression on '+' and '-' and keep which sub expressions are preceeded by a '+' and which are preceeded by a '-' (first sub expression is preceeded by a '+')¶
2) Split each sub expression on '*' and '/' and keep which sub expressions are preceeded by a '*' and which are preceeded by a '/' (first sub sub expressions are preceeded by a '*')¶
3) Compute the value of each sub expression as multiplications and divisions of sub sub expression (running product starting with a value 1 and then multiply or divided by each sub sub expression)¶
4) Compute the final value of the expression as addition and substractions of sub expressions (running sum starting with a value 0 and for which we add or substract the sub expressions)¶
In [ ]:
def calculate(s: str) -> int:
    splitted_add_sub = re.split('\+|\-', s)
    splits_add_sub = ["+"] + re.findall("\+|\-", s)

    total = 0
    for i in range(len(splitted_add_sub)):
        total_tmp = 1

        splitted_mult_div = re.split('\*|\/', splitted_add_sub[i])
        splits_mult_div = ["*"] + re.findall("\*|\/", splitted_add_sub[i])

        for j in range(len(splitted_mult_div)):
            if splits_mult_div[j] == "*":
                total_tmp *= int(splitted_mult_div[j])
            elif splits_mult_div[j] == "/":
                total_tmp = int(total_tmp / int(splitted_mult_div[j]))

        if splits_add_sub[i] == "+":
            total += int(total_tmp)
        elif splits_add_sub[i] == "-":
            total -= int(total_tmp)
    return(total)