NSI : algorithmes gloutons

Un algorithme est une suite finie et non ambiguë d’instructions et d’opérations permettant de résoudre une classe de problèmes. Le domaine qui étudie les algorithmes est appelé l’algorithmique.

Wikipédia

proposition correction algo rangement

objets=[3,7,6,3,4,8,5,9,2,2]
carton_max=11
nbre_cartons=5
def algo1_rangement():
    '''
    >>>algo1_rangement()
    [[3,7],[6,3,2],[4,5,2],[8],[9]]
    '''
    cartons=[[] for i in range(nbre_cartons)]
    # on parcoure les objets
    for objet in objets:
        objet_range=False
        # on parcoure les cartons
        for carton in cartons:
            # si le carton est dispo
            if sum(carton)+objet<=carton_max and objet_range==False:
                # on ajoute l'objet au carton
                carton.append(objet)
                objet_range=True
    # on retourne les cartons
    return cartons
    
objets=[3,7,6,3,4,8,5,9,2,2]
carton_max=11
nbre_cartons=5

def algo2():
# idem que algo1 mais avec juste des while
    cartons = [[] for i in range(5)]
    i = 0 
    while i < len(objets):
        objet = objets[i]
        j = 0  
        objet_range = False
        while j < len(cartons) and not objet_range:
            if sum(cartons[j]) + objet <= carton_max:
                cartons[j].append(objet) 
                objet_range = True
            j += 1
        i += 1

    return cartons

monnaie=[1,2,5,10,20,50,100,200]

def rendu_monnaie(somme_a_payer,somme_donnee):
    '''
    rendu_monnaie(22,50)
    [20,5,2,1]
    '''