Think of a Complex Number

complex numbers · division · reciprocal · conjugate · inverse operations

A party trick with complex numbers: "Think of a complex number. Multiply it by i. Add 2. What do you get? 1 + 3i? Then you started with 3 + i."

The trick is a recipe: a list of steps (name, w) applied in order to the secret number z:

step does w
("add", w) z = z + w a number
("mul", w) z = z * w a number, never 0
("div", w) z = z / w a number, never 0
("inv", None) z = 1 / z, the reciprocal None
("conj", None) z = z.conjugate(), the mirror image \bar z None

Python divides complex numbers directly: (1+3j) / 1j is (3-1j). By hand, multiply top and bottom by the conjugate of the bottom, which makes the bottom real: \frac{1}{a+bi} = \frac{a-bi}{a^2+b^2}.

Write undo_recipe(ops, result) that returns the secret number that the recipe ops turns into result. The tests always come from a real run of the recipe, so the secret number exists and is unique.

Examples

Input:  ops = [("mul", 1j), ("add", 2)], result = 1+3j
Output: (3+1j)
Explanation: this solves 1j * z + 2 = 1+3j. Check: (3+1j) * 1j = -1+3j, plus 2 is 1+3j.

Input:  ops = [("conj", None), ("inv", None)], result = 0.2+0.4j
Output: (1+2j)
Explanation: the mirror image of 1+2j is 1-2j, and 1 / (1-2j) = (1+2j) / 5 = 0.2+0.4j.

Constraints

  • 0 <= len(ops) <= 1000
  • answers are compared with a tolerance of 1e-6; do not round

Goals

  • Divide by a complex number and take its reciprocal 1/z
  • Undo a sequence of operations by undoing each step in reverse order
  • Solve a linear equation a*z + b = c for a complex z
Starting Python…