# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Short truncated series in h, stored as Taylor coefficients in increasing order."""

import math


def coefficients(value, length):
    if isinstance(value, Series):
        return value.coefficients
    return (value,) + (0.0,) * (length - 1)


class Series:
    def __init__(self, values):
        self.coefficients = tuple(values)

    def __add__(self, other):
        return Series(x + y for x, y in zip(self.coefficients, coefficients(other, len(self.coefficients)), strict=True))

    __radd__ = __add__

    def __neg__(self):
        return Series(-x for x in self.coefficients)

    def __sub__(self, other):
        return self + (-other)

    def __rsub__(self, other):
        return -self + other

    def __mul__(self, other):
        x = self.coefficients
        if not isinstance(other, Series):
            return Series(value * other for value in x)
        y = other.coefficients
        return Series(sum(x[j] * y[k - j] for j in range(k + 1)) for k in range(len(x)))

    __rmul__ = __mul__

    def __truediv__(self, other):
        x = self.coefficients
        if not isinstance(other, Series):
            return Series(value / other for value in x)
        y = other.coefficients
        quotient = []
        for k, value in enumerate(x):
            remainder = value - sum(quotient[j] * y[k - j] for j in range(k))
            quotient.append(remainder / y[0])
        return Series(quotient)

    def __rtruediv__(self, other):
        return Series(coefficients(other, len(self.coefficients))) / self

    def __pow__(self, power):
        if not isinstance(power, int):
            return NotImplemented
        result = 1
        for _ in range(abs(power)):
            result = result * self
        return 1 / result if power < 0 else result


def exp(value):
    if not isinstance(value, Series):
        return math.exp(value)
    x = value.coefficients
    out = [math.exp(x[0])]
    for k in range(1, len(x)):
        out.append(sum(j * x[j] * out[k - j] for j in range(1, k + 1)) / k)
    return Series(out)


def _sin_cos(value):
    x = value.coefficients
    sine, cosine = [math.sin(x[0])], [math.cos(x[0])]
    for k in range(1, len(x)):
        sine.append(sum(j * x[j] * cosine[k - j] for j in range(1, k + 1)) / k)
        cosine.append(-sum(j * x[j] * sine[k - j] for j in range(1, k + 1)) / k)
    return Series(sine), Series(cosine)


def sin(value):
    return _sin_cos(value)[0] if isinstance(value, Series) else math.sin(value)


def cos(value):
    return _sin_cos(value)[1] if isinstance(value, Series) else math.cos(value)
