Ctrl K

Simplify a Letter Polynomial

Hard
You get a formula formula built from non-negative integers, variables (strings of lowercase English letters), the signs +, -, * and round brackets. Numbers, variables and signs are separated by exactly one space; brackets sit right against what they enclose: (a + 2) * b. There is no unary minus, and a variable never has a coefficient glued to it (2x never appears). Some variables are known: variable known[i] equals values[i]. Substitute them, expand the brackets (brackets first, then multiplication, then addition and subtraction), collect like terms and return the result as a list of term strings: - a term is its coefficient followed by its variables in alphabetical order, joined with *: -3*a*b*b. A coefficient of 1 is still written: 1*x. The constant term is just a number: 7; - terms go by falling degree (the number of variables, counting repeats); terms of equal degree go in lexicographic order of their text without the coefficient; the constant term comes last; - terms with a zero coefficient are left out, so a formula equal to zero gives an empty list.
Example 1
formula="speed * time - 3 * time + 4", known=["speed"], values=[5] → ['2*time', '4']

With speed = 5 this is 5·time - 3·time + 4 = 2·time + 4. The degree-1 term goes first, then the constant.

Example 2
formula="(b + a) * (a - 2)", known=[], values=[] → ['1*a*a', '1*a*b', '-2*a', '-2*b']

Expanding gives a·a + a·b - 2·a - 2·b. Inside a term the variables are sorted (a*b, not b*a); terms go by falling degree, and alphabetically within a degree.

Example 3
formula="x * x - y", known=["x", "y"], values=[3, 9] → []

9 - 9 = 0, and terms with a zero coefficient are left out, so the answer is empty.

Constraints
  • 1 ≤ len(formula) ≤ 250
  • formula consists of lowercase English letters, digits, +, -, *, (, ) and spaces, is written as described and has no leading or trailing spaces
  • 0 ≤ len(known) = len(values) ≤ 100
  • The names in known are distinct, 1 ≤ len(known[i]) ≤ 20, lowercase English letters only
  • -100 ≤ values[i] ≤ 100
  • Every coefficient met along the way lies in [-2³¹, 2³¹ - 1]
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPlus-Minus Calculator With Brackets HardA Calculator With Brackets and Variables HardCalculator With Brackets and Four Operations HardAmount in Words HardElement Tally From a Formula Hard
loading Python…
Input
formula="speed * time - 3 * time + 4", known=["speed"], values=[5]
Expected
['2*time', '4']

Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.