"""Week 2: Recursion. Base case, recursive case, and trust the smaller call."""
from __future__ import annotations

from functools import lru_cache
from typing import List, Tuple


def factorial(n: int) -> int:
    if n < 0:
        raise ValueError("n must be non-negative")
    return 1 if n <= 1 else n * factorial(n - 1)


@lru_cache(maxsize=None)
def fibonacci(n: int) -> int:
    """Memoised: O(n) calls instead of O(2^n)."""
    return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)


def sum_digits(n: int) -> int:
    n = abs(n)
    return n if n < 10 else n % 10 + sum_digits(n // 10)


def is_palindrome(s: str) -> bool:
    return len(s) < 2 or (s[0] == s[-1] and is_palindrome(s[1:-1]))


def reverse_string(s: str) -> str:
    return s if len(s) <= 1 else reverse_string(s[1:]) + s[0]


def power_set(items: List[int]) -> List[List[int]]:
    """Each element is either excluded or included: 2^n subsets."""
    if not items:
        return [[]]
    rest = power_set(items[1:])
    return rest + [[items[0]] + subset for subset in rest]


def permutations(items: List[int]) -> List[List[int]]:
    if len(items) <= 1:
        return [items[:]]
    out = []
    for i, x in enumerate(items):
        for perm in permutations(items[:i] + items[i + 1:]):
            out.append([x] + perm)
    return out


def tower_of_hanoi(n: int, source: str = "A", target: str = "C", spare: str = "B") -> List[Tuple[str, str]]:
    """Move n-1 discs out of the way, move the largest, move n-1 back on top: 2^n - 1 moves."""
    if n == 0:
        return []
    return (tower_of_hanoi(n - 1, source, spare, target)
            + [(source, target)]
            + tower_of_hanoi(n - 1, spare, target, source))


def flatten(nested) -> list:
    """Flatten arbitrarily nested lists."""
    out = []
    for item in nested:
        if isinstance(item, list):
            out.extend(flatten(item))
        else:
            out.append(item)
    return out
