Algorithm


Problem Name: 770. Basic Calculator IV

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 [].

Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].

 

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"]

 

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

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const basicCalculatorIV = function (expression, evalvars, evalints) {
  // Tokenise and get list of unresolved variable names
  let [variables, it] = (function () {
    let variables = []
    let evalMap = new Map(evalvars.map((name, i) => [name, evalints[i]]))
    let tokens = expression.match(/\w+|\d+|\S/g)
    // Resolve occurrences of eval vars
    for (let i = 0; i  <  tokens.length; i++) {
      let token = tokens[i]
      if (token[0] >= 'A') {
        let num = evalMap.get(token)
        if (num !== undefined) {
          tokens[i] = num
        } else {
          variables.push(tokens[i])
        }
      }
    }
    return [[...new Set(variables)].sort(), tokens.values()] // array & iterator
  })()
  // Map each unknown variable to a sequential ID:
  let variableMap = new Map(variables.map((name, i) => [name, i]))

  // Parse tokens into Polynomial instance, and get output in required format
  return (function parse(sign = 1) {
    function parseTerm(sign = 1) {
      let token = it.next().value
      if (token === '(') return parse(sign)
      let term = new Term(sign)
      if (typeof token === 'string' && token >= 'A') {
        term.setVar(variableMap.get(token))
      } else {
        term.setCoefficient(+token)
      }
      return new Polynomial([term])
    }

    let polynomial = new Polynomial()
    let term = parseTerm(sign)
    for (let token; (token = it.next().value) && token !== ')'; ) {
      if (token === '*') {
        term.mul(parseTerm(1))
      } else {
        polynomial.add(term)
        term = parseTerm(token === '+' ? sign : -sign)
      }
    }
    return polynomial.add(term)
  })().output(variables)
}
class Term {
  constructor(coefficient, variables = [], degree = 0) {
    this.variables = variables
    this.coefficient = coefficient
    this.degree = degree
  }
  setVar(id) {
    while (this.variables.length  < = id) this.variables.push(0)
    this.variables[id]++
    this.degree++
  }
  setCoefficient(coefficient) {
    this.coefficient *= coefficient
  }
  clone() {
    return new Term(this.coefficient, [...this.variables], this.degree)
  }
  mul(term) {
    let n = term.variables.length
    while (this.variables.length < n) this.variables.push(0)
    for (let i = 0; i < n; i++) {
      this.variables[i] += term.variables[i]
    }
    this.degree += term.degree
    this.coefficient *= term.coefficient
    return this
  }
  cmp(term) {
    let diff = term.degree - this.degree
    if (diff) return Math.sign(diff)
    for (let i = 0; i  <  this.variables.length; i++) {
      diff = term.variables[i] - this.variables[i]
      if (diff) return Math.sign(diff)
    }
    return 0
  }
  format(variableNames) {
    return !this.coefficient
      ? ''
      : this.coefficient +
          this.variables.map((count, i) =>
            ('*' + variableNames[i]).repeat(count)
          ).join``
  }
}

class Polynomial {
  constructor(terms = []) {
    this.terms = terms
  }
  addTerm(term) {
    let terms = this.terms
    // binary search
    let low = 0
    let high = terms.length
    while (low < high) {
      let mid = (low + high) >> 1
      let diff = terms[mid].cmp(term)
      if (diff === 0) {
        terms[mid].coefficient += term.coefficient
        return this
      } else if (diff < 0) {
        low = mid + 1
      } else {
        high = mid
      }
    }
    terms.splice(low, 0, term)
    return this
  }
  add(polynomial) {
    for (let term of polynomial.terms) {
      this.addTerm(term)
    }
    return this
  }
  mul(polynomial) {
    let orig = new Polynomial(this.terms)
    this.terms = [] // clear
    for (let term1 of polynomial.terms) {
      for (let term2 of orig.terms) {
        this.addTerm(term1.clone().mul(term2))
      }
    }
    return this
  }
  output(variableNames) {
    return this.terms.map((term) => term.format(variableNames)).filter(Boolean)
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]

Output

x
+
cmd
["-1*a","14"]

#2 Code Example with Python Programming

Code - Python Programming


class Solution(object):
    def basicCalculatorIV(self, s, evalvars, evalints):
        s.strip()
        d = dict(zip(evalvars, evalints))
        s = s.replace(' ', '')
        ts = re.findall('\u005Cd+|[-()+*]|[^-()+*]+', s)
        
        def add(p, q):
            i, j = 0, 0
            r = []
            while i < len(p) and j < len(q):
                v, c = p[i]
                v2, c2 = q[j]
                if v == v2:
                    if c + c2 != 0:
                        r.append((v, c + c2))
                    i += 1
                    j += 1
                elif len(v) > len(v2) or len(v) == len(v2) and v < v2:
                    r.append(p[i])
                    i += 1
                else:
                    r.append(q[j])
                    j += 1
                            
            r += p[i:]
            r += q[j:]
            return r

        def neg(p):
            r = []
            for v, c in p:
                r.append((v, -c))
            return r

        def sub(p, q):
            return add(p, neg(q))

        def mult(p, q):
            r = []
            for v, c in p:
                for v2, c2 in q:
                    r = add(r, [(sorted(v + v2), c * c2)])
            return r
            
        def prec(c):
            return 0 if c in [')'] else 1 if c in ['+', '-'] else 2
            
        i = 0 
        def expr(p):
            nonlocal i, ts
            if ts[i] == '(':
                i += 1
                v = expr(0)
                i += 1
            elif ts[i] == '-':
                i += 1
                v = neg(expr(3))
            elif re.match('\u005Cd+', ts[i]):
                if ts[i] != '0':
                    v = [([], int(ts[i]))]
                else:
                    v = []
            else:
                if ts[i] in d:
                    if d[ts[i]] != 0:
                        v = [([], d[ts[i]])]
                    else:
                        v  = []
                else:
                    v = [([ts[i]], 1)]
            while i < len(ts) - 2 and prec(ts[i+1]) > p:
                op = ts[i+1]
                i += 2
                v2 = expr(prec(op))
                if op == '+': v = add(v, v2)
                if op == '-': v = sub(v, v2)
                if op == '*': v = mult(v, v2)
                
            return v

        def tostrings(p):
            r = []
            for v, c in p:
                if v == []:
                    r.append(str(c))
                else:
                    r.append(str(c) + '*' + '*'.join(v))
            return r
        
        return tostrings(expr(0))
Copy The Code & Try With Live Editor

Input

x
+
cmd
expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]

Output

x
+
cmd
["-1*a","14"]
Advertisements

Demonstration


Previous
#769 Leetcode Max Chunks To Make Sorted Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#771 Leetcode Jewels and Stones Solution in C, C++, Java, JavaScript, Python, C# Leetcode