15109 - Symbolic Differentiation   

Description

Amiya is so tired with work already, but now she has to also study for Calculus finals. But luckily, you offered a way to help her with a program that could help her do her homeworks.

Your job is to build a small class hierarchy for expressions and use it to compute symbolic derivatives.

Create an abstract base class Expr and these subclasses:

Class
Meaning
Fields
Const(value)
integer constant
value: int
Var(name)
variable
name: str (a single lowercase letter)
Add(left, right)
left + right
two Expr
Mul(left, right)
left * right
two Expr
Pow(base, exp)
base ^ exp
an Expr and a positive integer exp >= 1 

Every class implements a recursive method derivative(var) that returns a new Expr

(the derivative with respect to the variable named var). It must not modify the original expression.

Differentiation rules to implement

Let d(e) mean e.derivative(var).

Expression
Derivative `d(e)`
Const(c)
0
Var(x)
1 if the name equals var, otherwise 0
Add(a, b)
d(a) + d(b)
Mul(a, b)
d(a) * b + a * d(b)
Pow(a, n)
(n * a^(n-1)) * d(a)

 

Examples:

d/dx (x^3) = (3 * x^2) * 1 -> 3 * x^2

d/dx ((x + 1)^3) = (3 * (x + 1)^2) * (1 + 0) -> 3 * (x + 1)^2 (chain rule: multiply by d(x + 1))

d/dx (x * x) = 1 * x + x * 1 -> x + x

d/dx (y) = 0 (y is a different variable)

 

Required simplification

The derivative rules above produce many 0 and 1 factors. To make the printed output unique,

build every new node only through the helper functions below (they are in the template).

Each helper simplifies when it builds the node:

make_add(a, b):

1. a and b are both numbers -> Const(a.value + b.value) make_add(2, 3) = 5

2. a is the number 0 -> b make_add(0, x) = x

3. b is the number 0 -> a make_add(x, 0) = x

4. otherwise -> Add(a, b) make_add(x, y) = (+ x y)

 

make_mul(a, b):

1. a or b is the number 0 -> Const(0) make_mul(0, x) = 0

2. a and b are both numbers -> Const(a.value * b.value) make_mul(2, 3) = 6

3. a is the number 1 -> b make_mul(1, x) = x

4. b is the number 1 -> a make_mul(x, 1) = x

5. otherwise -> Mul(a, b) make_mul(x, y) = (* x y)

 

make_pow(a, n): (n is a plain Python int, not an Expr)

1. n == 0 -> Const(1) make_pow(x, 0) = 1

2. n == 1 -> a make_pow(x, 1) = x

3. a is a number -> Const(a.value ** n) make_pow(2, 3) = 8

4. otherwise -> Pow(a, n) make_pow(x, 2) = (^ x 2)

There is **NO** further simplification (no reordering, no like-term collection, no re-association).

There is **NO** further simplification (no reordering, no like-term collection, no re-association).

 

Subtrees copied from the input are used as-is and are never simplified: e.g. in the product rule

a and b are the original input subtrees. So (* (* 1 x) x) differentiated by x gives

(+ x (* 1 x)). The left x comes from make_mul(d(* 1 x), x) = make_mul(1, x) = x, the right

(* 1 x) is the untouched input subtree a.

 

The structure of the result is therefore fully determined by the rules table above, applied

exactly in the written order (e.g. product rule is d(a) * b + a * d(b) and not a * d(b) + d(a) * b;

power rule is (n * a^(n-1)) * d(a), i.e. make_mul(make_mul(Const(n), make_pow(a, n - 1)), d(a))).

 

Sample Code:

# ---------------------------------------------------------------------------
# Expression hierarchy
# ---------------------------------------------------------------------------
class Expr():
    def derivative(self, var: str) -> "Expr":
        """Return the derivative of this expression with respect to `var`."""
        # TODO
        pass
    def __str__(self) -> str:
        """Prefix notation, e.g. (+ x 1)."""
        parts = self._prefix_parts()
        if len(parts) == 1:                      # leaf: Const / Var
            return str(parts[0])
        return "(" + " ".join(str(p) for p in parts) + ")"


class Const(Expr):
    def __init__(self, value: int):
        self.value = value

    def derivative(self, var: str) -> Expr:
        # TODO: its a constant.
        pass

    def __str__(self) -> str:
        return str(self.value)


class Var(Expr):
    def __init__(self, name: str):
        self.name = name

    def derivative(self, var: str) -> Expr:
        # TODO: 1 if self.name == var else 0
        pass

    def __str__(self) -> str:
        return self.name


class Add(Expr):
    def __init__(self, left: Expr, right: Expr):
        self.left = left
        self.right = right

    def derivative(self, var: str) -> Expr:
        # TODO: sum rule, build the result with make_add
        pass

    def __str__(self) -> str:
        return f"(+ {self.left} {self.right})"


class Mul(Expr):
    def __init__(self, left: Expr, right: Expr):
        self.left = left
        self.right = right

    def derivative(self, var: str) -> Expr:
        # TODO: product rule derivative(a) * b + a * derivative(b), build with make_add / make_mul
        return make_mul(left.derivative, right)

    def __str__(self) -> str:
        return f"(* {self.left} {self.right})"


class Pow(Expr):
    def __init__(self, base: Expr, exp: int):
        self.base = base
        self.exp = exp  # positive integer

    def derivative(self, var: str) -> Expr:
        # TODO: power + chain rule  (n * base^(n-1)) * derivative(base)
        pass

    def __str__(self) -> str:
        return f"(^ {self.base} {self.exp})"


# ---------------------------------------------------------------------------
# Simplifying constructors (use these inside derivative())
# ---------------------------------------------------------------------------
def make_add(a: Expr, b: Expr) -> Expr:
    if isinstance(a, Const) and isinstance(b, Const):
        return Const(a.value + b.value)
    if isinstance(a, Const) and a.value == 0:
        return b
    if isinstance(b, Const) and b.value == 0:
        return a
    return Add(a, b)


def make_mul(a: Expr, b: Expr) -> Expr:
    if (isinstance(a, Const) and a.value == 0) or (isinstance(b, Const) and b.value == 0):
        return Const(0)
    if isinstance(a, Const) and isinstance(b, Const):
        return Const(a.value * b.value)
    if isinstance(a, Const) and a.value == 1:
        return b
    if isinstance(b, Const) and b.value == 1:
        return a
    return Mul(a, b)


def make_pow(a: Expr, n: int) -> Expr:
    if n == 0:
        return Const(1)
    if n == 1:
        return a
    if isinstance(a, Const):
        return Const(a.value ** n)
    return Pow(a, n)


# ---------------------------------------------------------------------------
# Parsing
# ---------------------------------------------------------------------------
def parse(text: str) -> Expr:
    tokens = text.replace("(", " ( ").replace(")", " ) ").split()
    pos = 0

    def read() -> Expr:
        nonlocal pos
        tok = tokens[pos]
        pos += 1
        if tok == "(":
            op = tokens[pos]
            pos += 1
            first = read()
            if op == "^":
                n = int(tokens[pos])
                pos += 1
                node = Pow(first, n)
            else:
                second = read()
                node = Add(first, second) if op == "+" else Mul(first, second)
            pos += 1  # skip ")"
            return node
        try:
            return Const(int(tok))
        except ValueError:
            return Var(tok)

    return read()


# ---------------------------------------------------------------------------
# Input / output
# ---------------------------------------------------------------------------
expr = input()
var = input.strip()
print(expr.derivative(var))

Input

<expression>
<variable>

Line 1: the expression in prefix (S-expression) notation, fully parenthesized, tokens separated by spaces:
  - integer constant (may be negative or zero): `5`, `-2`, `0`
  - variable: a single lowercase letter: `x`
  - `(+ A B)` sum, `(* A B)` product, `(^ A n)` power with integer literal `n >= 1`
Line 2: the variable to differentiate by (one lowercase letter). It may not appear in the expression at all.

Output

One line: the derivative in the same prefix notation, exactly as produced by the `__str__`
methods in the template (single spaces, no space after `(` or before `)`).

Sample Input  Download

Sample Output  Download




Discuss