calder.py

Created by bilouclic

Created on October 10, 2024

1.88 KB


# Créé par Mme Chavanon, le 25/09/2023 en Python 3.4
class Mobile_Calder():
    def __init__(self, masse : int, gauche=None, droite=None):
        assert ((gauche is None) and (droite is None)) or ((type(gauche) is Mobile_Calder) and (type(droite) is Mobile_Calder))
        self.masse = masse
        self.gauche = gauche
        self.droite = droite
    def __str__(self) -> str:
        s= "[" + str(self.masse)
        if not(self.gauche is None) and not(self.droite is None):
            s = s + " " + str(self.gauche) + " " + str(self.droite)
        return s + "]"
    def masse_totale(self) -> int:
        m = self.masse
        if not(self.gauche is None) and not(self.droite is None):
            m = m + self.gauche.masse_totale() + self.droite.masse_totale()
        return m
    def stable(self) -> (bool,int) :
        ''' Cette fonction renvoie True et la masse totale du mobile s'il est équilibré
                                   False, -1 sinon
        '''
        if self.gauche is None :
            # cas d'un mobile composé d'un seul solide
            return True, self.masse
        else :
            # cas d'une barre à laquelle sont suspendus deux sous-mobiles
            b1, m1 = self.gauche.stable()
            if b1 == True :
                b2, m2 = self.droite.stable()
                if (b2 == True) and (m1 == m2):
                    return True, m1 + m2 + self.masse
            return False, -1


if __name__ == "__main__":
    m1 = Mobile_Calder(30); print(m1)
    m2 = Mobile_Calder(3, Mobile_Calder(32), m1); print(m2)
    m2bis = Mobile_Calder(2, Mobile_Calder(14),
                             Mobile_Calder(2, Mobile_Calder(6), Mobile_Calder(6)))
    m3 = Mobile_Calder(4, Mobile_Calder(3, m1, m1), Mobile_Calder(3, m2bis, m1))
    print(m3)
    print(m1.masse_totale(), m2.masse_totale(), m3.masse_totale())
    print(m1.stable(), m2.stable(), m3.stable())

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.