#Correction CC Python P8 - 2022/2023
import numpy as np
from numpy import linalg as ln
import matplotlib.pyplot as plt



########################################################
# Exercice 1

def pythaliste(n):
    '''
    Renvoie la liste des triplets de Pythagore avec 
    $a \leq b$ et $c \leq n$.
    '''
    L = []
    for c in range(1, n + 1):
        for a in range(1, int(c/(2**.5)) + 1):
            d = c**2 - a**2
            b = int(d**.5) 
            if b**2 == d:
                L.append([a, b, c])
    return L


def pythaliste_prem(n):
    '''
    Retire les triplets ayant un diviseur commun ; 
    ceux-ci sont construits par multiplication.
    Renvoie la liste ainsi netoyee.
    '''
    L = pythaliste(n)
    for t in L:
        c = t[2]
        for k in range(2, n//c + 1):
            kt = [k*t[0], k*t[1], k*c]
            L.remove(kt)
    return L


def pytha_somme(n):
    L = pythaliste(n)
    result = []
    for t in L:
        if t[0] + t[1] + t[2] == n:
            result.append(t)
    return result


def pytha_max(n):
    '''
    L est la liste des triplets avec $c\leq n$ et dont la somme vaut n.
    P est la liste des produits des composantes de $t \in L$.
    j est l'indice de l'element maximal de P.
    Renvoie $L[j]$.
    '''
    L = pytha_somme(n)
    if L == []:
        return None
    else:
        P = []
        for t in L:
            P.append(t[0]*t[1]*t[2])
        j = P.index(max(P))
    return L[j]


### tests
n = 500
L = pythaliste(n)
print(f"il y a {len(L)} triplets avec c plus petit que {n}\n")
L = pythaliste_prem(n)
print(f"il y a {len(L)} triplets sans diviseur commun avec c plus petit que {n} : \n{L}\n")

n = 30
print(f"pour n = {n}, pytha_somme renvoie {pytha_somme(n)}\n")
# print(pytha_max(30))

n = 1
while pytha_max(n) == None:
    n = n + 1
print(f"le premier triplet de Pythagore est {pytha_max(n)} ; "
      + f"on l'obtient en invoquant pytha_max({n})" )


n = 1
while len(pytha_somme(n)) <= 1:
    n = n + 1
print(f"le premier n pour lequel pytha_somme renvoie une liste ayant au moins deux triplets est {n}")
print(*pytha_somme(n))
