"""Les six portes de la leçon 4.4, codées directement avec numpy, et un affichage lisible."""

import numpy as np

X = np.array([[0, 1],
              [1, 0]])
Y = np.array([[0, -1j],
              [1j, 0]])
Z = np.array([[1, 0],
              [0, -1]])
H = np.array([[1, 1],
              [1, -1]]) / np.sqrt(2)
S = np.array([[1, 0],
              [0, 1j]])
T = np.array([[1, 0],
              [0, np.exp(1j * np.pi / 4)]])

PLUS = np.array([1, 1]) / np.sqrt(2)    # |+⟩ (leçon 2.5)
MINUS = np.array([1, -1]) / np.sqrt(2)  # |−⟩


def fmt(z):
    """Un nombre arrondi à 3 décimales, sans partie nulle ni « -0 » : 0.6, 0.8j, 0.6+0.8j."""
    z = complex(np.round(complex(z), 3))
    re, im = z.real + 0.0, z.imag + 0.0
    if im == 0:
        return f"{re:g}"
    if re == 0:
        return f"{im:g}j"
    return f"{re:g}{im:+g}j"


def show(array):
    """Un vecteur ou une matrice, écrit avec fmt : [[0.6, 0.8j], [0.8j, 0.6]]."""
    array = np.asarray(array)
    if array.ndim == 1:
        return "[" + ", ".join(fmt(z) for z in array) + "]"
    return "[" + ", ".join(show(row) for row in array) + "]"
