Basic Calculator IV Problem
Description
LeetCode Problem 770.
Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"]
- An expression alternates chunks and symbols, with a space separating each chunk and symbol.
- A chunk is either an expression in parentheses, a variable, or a non-negative integer.
- A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x".
Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.
- For example, expression = "1 + 2 * 3" has an answer of ["7"].
The format of the output is as follows:
- For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
- For example, we would never write a term like "b*a*c", only "a*b*c".
- Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
- For example, "a*a*b*c" has degree 4.
- The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.
- An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"].
- Terms (including constant terms) with coefficient 0 are not included.
- For example, an expression of "0" has an output of [].
Example 1:
Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output: ["-1*a","14"]
Example 2:
Input: expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12]
Output: ["-1*pressure","5"]
Example 3:
Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output: ["1*e*e","-64"]
Example 4:
Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
Output: ["5*a*b*c"]
Example 5:
Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", evalvars = [], evalints = []
Output: ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"]
Constraints:
- 1 <= expression.length <= 250
- expression consists of lowercase English letters, digits, '+', '-', '*', '(', ')', ' '.
- expression does not contain any leading or trailing spaces.
- All the tokens in expression are separated by a single space.
- 0 <= evalvars.length <= 100
- 1 <= evalvars[i].length <= 20
- evalvars[i] consists of lowercase English letters.
- evalints.length == evalvars.length
- -100 <= evalints[i] <= 100
Solution
Approach: Recursive Descent over Polynomials
Evaluate the expression the way a calculator would, except that every intermediate value is a polynomial instead of a number. Represent a polynomial as a map from a term key to its coefficient, where the key is the term's variables in sorted order joined by * ("a*a*b") and the constant term has the key "". Keeping the variables sorted makes a*b and b*a the same key, so like terms combine automatically.
First put spaces around every parenthesis, so "(e + 8)" splits into the tokens ( e + 8 ). Then parse with one function per precedence level:
parseExpression: a term, then any number of+ term/- term; add or subtract the coefficients key by key.parseTerm: a factor, then any number of* factor; multiply the polynomials, pairing every term of one with every term of the other (concatenate and re-sort the variables, multiply the coefficients).parseFactor:( expression ), a number (a constant), or a variable. A variable listed inevalvarsbecomes the constant fromevalints; any other variable becomes{name: 1}.
Splitting the work this way gives * higher precedence than + and - without any operator stack.
To build the answer, drop terms whose coefficient is 0 (for example, a - a cancels completely), then sort the rest by degree, highest first, and break ties by comparing the keys as strings. Because * sorts before every lowercase letter, comparing the joined keys gives the same order as comparing the variable lists one variable at a time. Format each term as coef*key, or just coef for the constant. Writing the coefficient 1 is required, as in "1*e*e".
Complexity: the parser reads each of the n tokens once; multiplying polynomials with P and Q terms takes O(P · Q · d log d) time, where d is the degree of the terms, and this dominates when the expression multiplies many sums. Space is O(T · d) for the largest polynomial built, with T terms.
class Solution:
def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:
known = dict(zip(evalvars, evalints)) # variables that have a value
# Put spaces around the parentheses so that every token is separated by a space.
tokens = expression.replace("(", "( ").replace(")", " )").split()
pos = 0 # index of the next token to read
# A polynomial maps a term key to its coefficient. The key is the term's
# variables in sorted order joined by "*", and "" for the constant term.
def variables_of(key: str) -> List[str]:
return key.split("*") if key else []
def multiply(p: Dict[str, int], q: Dict[str, int]) -> Dict[str, int]:
product = {}
for key1, coef1 in p.items():
for key2, coef2 in q.items():
key = "*".join(sorted(variables_of(key1) + variables_of(key2)))
product[key] = product.get(key, 0) + coef1 * coef2
return product
def parse_expression() -> Dict[str, int]:
"""term (('+' | '-') term)*"""
nonlocal pos
result = parse_term()
while pos < len(tokens) and tokens[pos] in ("+", "-"):
sign = 1 if tokens[pos] == "+" else -1
pos += 1
for key, coef in parse_term().items():
result[key] = result.get(key, 0) + sign * coef
return result
def parse_term() -> Dict[str, int]:
"""factor ('*' factor)*"""
nonlocal pos
result = parse_factor()
while pos < len(tokens) and tokens[pos] == "*":
pos += 1
result = multiply(result, parse_factor())
return result
def parse_factor() -> Dict[str, int]:
"""'(' expression ')' | number | variable"""
nonlocal pos
token = tokens[pos]
pos += 1
if token == "(":
inner = parse_expression()
pos += 1 # skip the ")"
return inner
if token.isdigit():
return {"": int(token)}
if token in known:
return {"": known[token]}
return {token: 1}
polynomial = parse_expression()
def degree(key: str) -> int:
return len(variables_of(key))
# Highest degree first, then lexicographic order of the variables.
keys = sorted((key for key, coef in polynomial.items() if coef != 0),
key=lambda key: (-degree(key), key))
answer = []
for key in keys:
coef = polynomial[key]
answer.append(str(coef) if key == "" else str(coef) + "*" + key)
return answer
Now write it from memory
Close the write-up and solve it yourself against the tests.