"""Generate the Dyck paths of semilength n, given on the command line, and
print each one drawn in text above its Dyck word, then the number of paths
and the Catalan number C(n)."""

import sys
from math import comb


def dyck_paths(n, path="", ups=0, height=0):
    """Generate the Dyck paths of semilength n as strings of / (an up step)
    and \\ (a down step). The recursion continues a partial path, which has
    ups up steps and ends at the given height."""
    if len(path) == 2 * n:
        yield path
        return
    if ups < n:
        # An up step, if any are left.
        yield from dyck_paths(n, path + "/", ups + 1, height + 1)
    if height > 0:
        # A down step, if the path is above the axis.
        yield from dyck_paths(n, path + "\\", ups, height - 1)


def draw_mountains(path):
    """Return the path drawn in text, as lines of / and \\ from the top."""
    rows, height = {}, 0
    for k, step in enumerate(path):
        # An up step is drawn in the row of the level it starts from, and a
        # down step in the row of the level it ends at.
        if step == "\\":
            height -= 1
        rows.setdefault(height, [" "] * len(path))[k] = step
        if step == "/":
            height += 1
    return "\n".join("".join(rows[h]).rstrip()
                     for h in sorted(rows, reverse=True))


def dyck_word(path):
    """Return the path written as a string of balanced brackets."""
    return path.replace("/", "(").replace("\\", ")")


if __name__ == "__main__":
    n = int(sys.argv[1])
    count = 0
    for path in dyck_paths(n):
        print(draw_mountains(path))
        print(dyck_word(path), end="\n\n")
        count += 1
    print(f"Number of paths: {count}; C({n}) = {comb(2 * n, n) // (n + 1)}")
