Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • master
1 result

Target

Select target project
No results found
Select Git revision
  • master
1 result
Show changes
124 files
+ 344733
1443
Compare changes
  • Side-by-side
  • Inline

Files

+27 −0
Original line number Diff line number Diff line
# INF-TC1

## Installation

* La distribution Anaconda offre cet avantage en étant multi-plateformes (Windows, Mac, Linux) et disposant de tous les outils dont vous aurez besoin en Informatique au cours du semestre (interpréteur Python, éditeur Spyder, divers modules). Vous obtiendrez la dernière version sur ce site : https://www.anaconda.com/download/

* Nous vous demandons donc de l’installer sur vos ordinateurs et de vérifier son fonctionnement (l’exécution d’un code simple devrait suffire) avant votre première séance de TD.

* Concerant l'éditeur de code Python, vous pouvez utiliser Spyder inclu dans Anaconda, mais vous pouvez aussi télécharger et installer Microsoft Code qui est une excellente alternative : https://code.visualstudio.com/download


## Aides en informatique

* Des [transparents d'aide](aide-informatique.pdf)
* Une vidéo de présentation de ces transparents https://replay.ec-lyon.fr/video/0920-aides-en-informatique/ 

## Livres

Les livres suivants sont disponibles sous forme de pdf et couvrent les points abordés en cours et en TD :

- [Think Python](books/thinkpython2.pdf), 2nd edition, par Allen B. Downey
- [Python for Everybody](books/pythonlearn.pdf), par Charles Severance
- [Problem Solving with Algorithms and Data Structures using Python](books/problemsolving.pdf), par Brad Miller et David Ranum
- [ODS Pyhon](books/ods-python.pdf), par Pat Morin ([url](https://opendatastructures.org/ods-python/))

Autres ressources :

- https://en.wikibooks.org/wiki/Algorithms/
- [computer science books](https://freecomputerbooks.com/compscAlgorithmBooks.html)
 No newline at end of file

TD01/Readme.md

0 → 100644
+0 −0
Original line number Diff line number Diff line

TD01/code/addition.py

deleted100644 → 0
+0 −17
Original line number Diff line number Diff line
def addition(a, b):
    return a + b
    
def addition_inf(*argv):
    res = 0
    for arg in argv:  
        res += arg
    return res

if __name__=="__main__": 
    assert addition(1, 2) == 3
    assert not addition(1, 2) == 2

    assert addition_inf(1, 1, 1) == 3
    assert not addition_inf(1, 1, 1) == 2

    assert addition_inf(1, 1, 1) == addition(1, 2)
 No newline at end of file

TD01/code/chaines-valide.py

deleted100644 → 0
+0 −10
Original line number Diff line number Diff line
def valide(seq):
    """Retourne True si séquence ADN."""
    ret = len(seq) != 0
    for c in seq:
        ret = (ret and True) if (c in "atgc") else False
    return ret

if __name__=="__main__": 
    assert valide("atgc")
    assert not valide("atgcz")

TD01/code/commentaires.py

deleted100644 → 0
+0 −15
Original line number Diff line number Diff line
# Un commentaire court commence par un # et se limite à la fin de la ligne

"""
On peut aussi créer un commentaire long = une zone de 
commentaires  sur plusieurs lignes placées
entre une paire de triple-guillements dont le second suit :
"""

# Remarques : 
# Un ';' à la fin d'une ligne rend la ligne muette (pas d'affichage des résultats). 
# Il permet également de placer plusieurs expressions sur la même ligne.

# Si vous placez un commentaire immédiatement après la signature d'une fonction} 
# (ou une méthode, une classe, etc.) entre un couple de  """, 
# votre commentaire (appelé docstring) devient accessible avec help
 No newline at end of file
+0 −8
Original line number Diff line number Diff line
carres = []
for x in range(10):
    if x % 2:
        carres.append(x * x)

list(map(lambda x: x * x,  filter(lambda x: x % 2, range(10))))

[x * x for x in range(10) if x % 2]

TD01/code/comprehension.py

deleted100644 → 0
+0 −37
Original line number Diff line number Diff line
S = [x**2 for x in range(10)]
V = [2**i for i in range(13)]
M = [x for x in S if x % 2 == 0]

print(S); print(V); print(M)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
# [0, 4, 16, 36, 64]


S = {x**2 for x in range(10)}           # {} au lieu de [] : on veut un ensemble
print(S)
# {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
type(S)
#set

V = (2**i for i in range(13))
print(V)
# <generator object <genexpr> at 0x7f7bb55edc18>

type(V)
# generator

# On peut mieux comprendre les listes en compréhension à travers leurs fonctions équivalentes
S = []
for i in range(10):
    S.append(i*2)

# Et 
S = [i*2 for i in range(10)]

S
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

[c for c in "foobar"]

# Donne ['f', 'o', 'o', 'b', 'a', 'r']
 No newline at end of file

TD01/code/dict.py

deleted100644 → 0
+0 −62
Original line number Diff line number Diff line
# Trois fonctions importantes sur les dicts  : keys(), values() et items()

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
# True

capitals = {'Iowa':'DesMoines','Wisconsin':'Madison'}
print(capitals['Iowa'])
# DesMoines

capitals['Utah']='SaltLakeCity'
print(capitals)
# {'Iowa': 'DesMoines', 'Utah': 'SaltLakeCity', 'Wisconsin': 'Madison'}

capitals['California']='Sacramento'
print(len(capitals))
# 4

for k in capitals:
    print(capitals[k]," is the capital of ", k)
# DesMoines  is the capital of  Iowa
# SaltLakeCity  is the capital of  Utah
# Madison  is the capital of  Wisconsin
# Sacramento  is the capital of  California

phone_ext={'david':1410, 'brad':1137}
phone_ext
# {'brad': 1137, 'david': 1410}

phone_ext.keys()                    # Renvoie les clés de phone_ext
# dict_keys(['brad', 'david'])

list(phone_ext.keys())
# ['brad', 'david']

"brad" in phone_ext
# True

1137 in phone_ext
# False                             # 1137 n'est pas une clé

phone_ext.values()                  # Renvoie les valeurs de phone_ext
# dict_values([1137, 1410])

list(phone_ext.values())
# [1137, 1410]

phone_ext.items()
# dict_items([('brad', 1137), ('david',1410)])

phone_ext.get("kent")
# Rien !    La clé n'y est pas.

phone_ext.get("kent","NO ENTRY")    # Si on veut récupérer la réponse en cas d'absence de la clé.
'NO ENTRY'

del phone_ext["david"]
phone_ext
 No newline at end of file

TD01/code/division.py

deleted100644 → 0
+0 −15
Original line number Diff line number Diff line
def division(x, y):
    return x / y

if __name__=="__main__": 
    try:
        r = division(2, 1)
        # division(2, 0)
        # division("2", "1")
    except ZeroDivisionError:
        print("Division par zero !")
    else:
        print("Le résultat est", r)
    finally:
        print("Clause finale")

TD01/code/exceptions.py

deleted100644 → 0
+0 −33
Original line number Diff line number Diff line
# https://docs.python.org/3/tutorial/errors.html
import addition

class Error(Exception):
    """Classe de base d'exceptions"""
    pass

class ValueTooSmallError(Error):
    """Si la valeur est trop petite"""
    pass

if __name__ == "__main__":

    a, b = 1, 2

    try:
        if a < 0 or b < 0:
            raise ValueTooSmallError
        # assert addition(a, b) == 3
        # assert not addition(a, b) == 4
        # addition(a, "c")

        # raise EnvironmentError
    except AssertionError:
        print("test non validé")
    except TypeError:
        print("problème de typage")
    except ValueTooSmallError:
        print("valeur trop petite")
    except:
        print("erreur inconnue")
    finally:
        print("c'est la fin, toujours exécuté")

TD01/code/fibo-comp.py

deleted100644 → 0
+0 −14
Original line number Diff line number Diff line
def fibo1(f2, f1, i):
    if i > 0:
        return fibo1(f1, f2+f1, i-1)
    else:
        return f2


def fibo2(f2, f1, i):
    while i > 0:
        f2, f1, i = f1, f2+f1, i-1
    return f2

print(fibo1(6))
print(fibo2(6))
 No newline at end of file

TD01/code/fibo-mem.py

deleted100644 → 0
+0 −23
Original line number Diff line number Diff line
def fib(n, lookup): 
  
    # Cas d'arrêt
    if n == 0 or n == 1 : 
        lookup[n] = n 
  
    # On calcule la valeur si pas déjà calculée
    if lookup[n] is None: 
        lookup[n] = fib(n-1 , lookup)  + fib(n-2 , lookup)  
  
    # On renvoie la n-eme valeur
    return lookup[n] 
  
def main(): 
    n = 6 
    max = 100
    # Initialise la table de cache
    lookup = [None]*(max)
    print("Le nombre de fibonacci est ", fib(n, lookup))
    # Le nombre de fibonacci est  8

if __name__=="__main__": 
    main() 
 No newline at end of file

TD01/code/file.py

deleted100644 → 0
+0 −31
Original line number Diff line number Diff line
class File():
    def __init__(self, values = []):
        self.__values = []
        for v in values:
            self.ajoute(v)

    def ajoute(self, v):
        self.__values.append(v)
        return v

    def supprime(self):
        v = self.__values.pop(0)
        return v

    def renvoie(self, critere = lambda x : True):
        for v in self.__values:
            if critere(v):
                return v
        return False

    def affiche(self):
        for v in self.__values:
            print(v)

    def taille(self): 
        return len(self.__values)

if __name__ == "__main__":
    f = File()
    for d in [1, 2, 3]:
        f.ajoute(d)

TD01/code/format.py

deleted100644 → 0
+0 −87
Original line number Diff line number Diff line
from math import pi

s = "Python"
s.center(10)         # centrer sur 10 positions
print(s)
# Donne -->'  Python  '

s.center(10,"*")       # centrer sur 10 positions en complétant par des '*'
# Donne -->'**Python**'
print(s)

s = "Training"
s.ljust(12)           # justifier à gauche sur 12 positions} 
# Donne -->'Training    '
print(s)

s.ljust(12,":")
# Donne -->'Training::::'

s = "Programming"
s.rjust(15)
# Donne -->'    Programming'
s.rjust(15, "~")
# Donne -->'~~~~Programming'

account_number = "43447879"
account_number.zfill(12)
# Donne -->'000043447879'

# Même chose avec rjust : 
account_number.rjust(12,"0")
# Donne -->'000043447879'

s = 'Hello, world.'
str(s)
# Donne -->'Hello, world.'

repr(s)
# Donne --> "'Hello, world.'"
str(1/7)
# Donne --> '0.14285714285714285'

r=2
print("La surface pour un rayon {rayon:3d} sera {surface:8.3f}".format(surface=r*r*pi, rayon=r))
# Donne -->  'La surface pour un rayon   2 sera   12.566'

x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print(s)
# Donne --> The value of x is 32.5, and y is 40000...

# Le repr() d'un string ajoute des quotes et backslashes:
hello = 'hello, world\n'
str(hello)
# Donne --> 'hello world\n'
repr(hello)
# Donne --> 'hello, world\\n' %*  {\color{magenta}  noter le double slash}    *)

# L'argument d'appel de repr() peut être n'importe quel objet  Python :
repr((x, y, ('spam', 'eggs')))
# Donne -->"(32.5, 40000, ('spam', 'eggs'))"

for x in range(1, 11):
    print(repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4))
# Donne -->
#  1   1    1
#  2   4    8 
#  3   9   27
#  4  16   64
#  5  25  125
#  6  36  216
#  7  49  343
#  8  64  512
#  9  81  729
# 10 100 1000

for x in range(1, 6):
    print(repr(x).rjust(2), end='#'*x+'\n')    # on ajoute x fois \# + \textbackslash n à la fin de chaque ligne}  *)

# Donne -->
#  1#
#  2##
#  3###
#  4####
#  5##### 
# 
 No newline at end of file

TD01/code/graphe-sim.py

deleted100644 → 0
+0 −70
Original line number Diff line number Diff line
# Par exemple pour Fool et Sage vous devez renvoyez le résultat suivant :
# 
# FOOL
# POOL
# POLL
# POLE
# PALE
# SALE
# SAGE
# 
# SOLUTION:

graph = {'A': ['B', 'C'],
  'B': ['C', 'D'],
  'C': ['D'],
  'D': ['C'],
  'E': ['F'],
  'F': ['C']
}

class Graphe(dict):
    def __init__(self, liens, noeuds):
        for v in liens:
            self[v] = set()
        for e in noeuds:
            self.ajout_noeud(e)

    def ajout_lien(self, lien):
        self[lien[0]].add(lien[1])
        self[lien[1]].add(lien[0])

    def ajout_noeud(self, noeud):
        self[noeud] = set()

def simGraphe(mots):
    d = {}
    g = Graphe(mots, [])

    for mot in mots:
        for i in range(len(mot)):
            groupe = mot[:i] + '_' + mot[i+1:]
            if groupe in d:
                d[groupe].append(mot)
            else:
                d[groupe] = [mot]

    for groupe in d.keys():
        for mot1 in d[groupe]:
            for mot2 in d[groupe]:
                if mot1 != mot2:
                    g.ajout_lien([mot1, mot2])
    return g

def chemin(graphe, source, destination, visite=None):

    if source == destination:
        return [destination]
    else:
        visite = visite or set()
        for s in graphe[source]:
                if s not in visite:
                    visite.add(s)
                    print("trace:", source + " > " + s)
                    sous_chemin = chemin(graphe, s, destination, visite)
                    if sous_chemin is not None:
                        return [source] + sous_chemin

print(chemin(simGraphe(["AA", "AB", "BC", "AC", "DD"]), "AA", "BC"))

# ['AA', 'AB', 'AC', 'BC']
 No newline at end of file

TD01/code/graphe_dico.py

deleted100644 → 0
+0 −25
Original line number Diff line number Diff line
G = {
    'A' : ['B','C', 'F'],
    'B' : ['D', 'E'],
    'C' : ['F'],
    'D' : ['G'],
    'E' : ['F'],
    'F' : ['G', 'H'],
    'G' : ['H'],
    'H' : []
}

v = set()

def traitement(v, G, n):
    if n not in v:
        v.add(n)
        print(n)
        for m in G[n]:
            traitement(v, G, m)

if __name__ == '__main__':
    traitement(v, G, 'A')

    if len(v) > 0:
        print("Que se passe-t-il ?")

TD01/code/liste-liee.py

deleted100644 → 0
+0 −33
Original line number Diff line number Diff line
class Node:
    def __init__(self, data = None, next = None):
        self.data = data
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    def listprint(self):
        printval = self.head
        while printval is not None:
            print(printval.dataval)
            printval = printval.nextval
    
    def push(self, n):
        if self.head is None:
            self.head = Node(n)
        else:
            node = self.head
            while node.next is not None:
                node = node.next
            node.next = Node(n)

    def detectLoop(self):
        s = set() 
        temp = self.head 
        while (temp):
            if (temp in s): 
                return True
            s.add(temp) 
            temp = temp.next
        return False
 No newline at end of file

TD01/code/listes-liee-boucle.py

deleted100644 → 0
+0 −15
Original line number Diff line number Diff line
from liste_liee import *

ll = liste_liee() # Ajout de données
ll.push(20) 
ll.push(4) 
ll.push(15) 
ll.push(10)
   
# Création d'une boucle
ll.head.next.next.next.next = ll.head; 
  
if( ll.detectLoop()): 
    print ("Il y a une boucle !") 
else : 
    print ("Pas de boucle ! ") 
 No newline at end of file

TD01/code/listes.py

deleted100644 → 0
+0 −5
Original line number Diff line number Diff line


L = []

L.ap    
 No newline at end of file

TD01/code/moyenne.py

deleted100644 → 0
+0 −10
Original line number Diff line number Diff line
# Calcul de la moyenne de deux entiers  

a=input('Donner la valeur de a : ')
b=input('Donner la valeur de b : ')
print('la moyenne = ', (int(a) + int(b))/2)  # int(a) : conversion de 'a' en entier

# Une seconde méthode : on convertit en lisant les valeurs en int
a=int(input('Donner la valeur de a : '))
b=int(input('Donner la valeur de b : '))
print('la moyenne = ', (a+b)/2) 

TD01/code/parite.py

deleted100644 → 0
+0 −18
Original line number Diff line number Diff line
def parite(a):
    """ Lire un entier au clavier et décider (et afficher) s'il est pair ou impair. """
    if (a%2 == 1):
        print(a, " est impair")
    else :
        print(a, " est pair")

if __name__=="__main__": 

    while True:
        try:
            a = int(input('Donner un entier  positif : '))
            parite(a)
            break
        except ValueError:
            print("Ce n'est pas un nombre valide.. ré-essayer !")
   
    
 No newline at end of file

TD01/code/pile.py

deleted100644 → 0
+0 −25
Original line number Diff line number Diff line
class Pile():
    def __init__(self, values = []):
        self.__values = []
        for v in values:
            self.ajoute(v)

    def ajoute(self, v):
        self.__values.append(v)
        return v

    def supprime(self):
        v = self.__values.pop()
        return v

    def affiche(self):
        for v in self.__values:
            print(v)

    def taille(self): 
        return len(self.__values)

if __name__ == "__main__":
    p = Pile()
    for d in [1, 2, 3]:
        p.ajoute(d)

TD01/code/premier.py

deleted100644 → 0
+0 −30
Original line number Diff line number Diff line
from math import sqrt

def premier(a):

    # si == 1 ou ==2
    if(a == 1 or a== 2):
        return True
    # si pair
    elif(a % 2 == 0):
        return False
    else:
        if (int(sqrt(a)) == sqrt(a)):
            return False
        
        for k in range(3, int(sqrt(a)+1), 2):
            if a % k == 0:
               return False
        
        return True 
    # autre

assert premier(1) == True
assert premier(2) == True
assert premier(4) == False
assert premier(9) == False

assert premier(3) == True
assert premier(20) == False
assert premier(23) == True
assert premier(6067) == True

TD01/code/racines.py

deleted100644 → 0
+0 −18
Original line number Diff line number Diff line
from math import sqrt;

def trinome(a, b, c):
    """ Résolution équation quadratique """
    delta = b**2 - 4*a*c
    if delta > 0.0:
        assert(a != 0)      
        racine_delta = sqrt(delta)
        return (2, (-b-racine_delta)/(2*a), (-b+racine_delta)/(2*a))
    elif delta < 0.0: return (0,)
    else: 
        assert(a != 0)     
        return (1, (-b/(2*a)))
    
if __name__ == "__main__":
    print(trinome(1.0, -3.0, 2.0))
    print(trinome(1.0, -2.0, 1.0))
    print(trinome(1.0, 1.0, 1.0))  
 No newline at end of file
+0 −27
Original line number Diff line number Diff line
def trouveOuDitOuInserer(sequence, val, inf=0, sup=None):
    if sup is None:
        sup = len(sequence)-1
    if sup < inf :
        return inf
    mid = (inf + sup) // 2  
    if sequence[mid] == val:  return mid
    if sequence[mid] < val:   inf = mid + 1
    else: sup = mid-1
    return trouveOuDitOuInserer(sequence, val, inf, sup)
3
ary = (2, 3, 4,  6, 7,9,10, 12, 13)
print('On cherche dans ', ary, ' et les places sont : ')
print('7 ', trouveOuDitOuInserer(ary, 7, 0, len(ary) -1));input('?'); 
print('2 ',trouveOuDitOuInserer(ary, 2, 0, len(ary) -1));input('?')
print('5 ',trouveOuDitOuInserer(ary, 5, 0, len(ary) -1));input('?')
print('15', trouveOuDitOuInserer(ary, 15, 0, len(ary) -1));input('?')
print('1', trouveOuDitOuInserer(ary, 1, 0, len(ary) -1));input('?')

""" tests
On cherche dans  (2, 3, 4, 6, 7, 9, 10, 12, 13) et les places sont : 
7  4
2  0
5  3
15 9
1  0
"""
 No newline at end of file

TD01/code/recherche-dichotomie.py

deleted100644 → 0
+0 −40
Original line number Diff line number Diff line
from random import randint;

def dichotomie(liste, val):
    print("La liste reçue : ",liste, ' de taille ', len(liste))
    if liste==[] : return False
    m=len(liste)//2
    print('\ton compare liste[',m,']=', liste[m], ' et ', val) 
    if liste[m] == val: return True
    elif liste[m] > val: return dichotomie(liste[:m], val)     # dans liste[:m], liste[m] n'est pas inclu.
    else: return dichotomie(liste[m+1:], val)                  # dans liste[X:],  liste[X]  est  inclu.
 
ll=[randint(1,50) for i in range(10)]  
ll.sort()
x=int(input("chercher une valeur entre 1 et 50 dans la liste " + repr(ll) + " ? : "))
print("La présence de  ", x, " dans la liste : ", ll, dichotomie(ll, x))    

"""  
# Et un cas de succès : 
chercher une valeur entre 1 et 50 dans la liste [4, 7, 10, 14, 19, 27, 31, 32, 35, 47] ? : 32
La liste reçue :  [4, 7, 10, 14, 19, 27, 31, 32, 35, 47]  de taille  10
on compare liste[ 5 ]= 27  et  32
La liste reçue :  [31, 32, 35, 47]  de taille  4
on compare liste[ 2 ]= 35  et  32
La liste reçue :  [31, 32]  de taille  2
on compare liste[ 1 ]= 32  et  32
La présence de   32  dans la liste :  [4, 7, 10, 14, 19, 27, 31, 32, 35, 47] True

# Et un cas d'échec :
chercher une valeur entre 1 et 50 dans la liste [22, 23, 30, 33, 37, 42, 42, 43, 47, 49] ? : 35
La liste reçue :  [22, 23, 30, 33, 37, 42, 42, 43, 47, 49]  de taille  10
on compare liste[ 5 ]= 42  et  35
La liste reçue :  [22, 23, 30, 33, 37]  de taille  5
on compare liste[ 2 ]= 30  et  35
La liste reçue :  [33, 37]  de taille  2
on compare liste[ 1 ]= 37  et  35
La liste reçue :  [33]  de taille  1
on compare liste[ 0 ]= 33  et  35
La liste reçue :  []  de taille  0
La présence de   35  dans la liste :  [22, 23, 30, 33, 37, 42, 42, 43, 47, 49] False
"""
 No newline at end of file

TD01/code/recherche-dico.py

deleted100644 → 0
+0 −16
Original line number Diff line number Diff line
def recherche(element, liste):
    a = 0
    b = len(liste)-1

    while a < b :
        m = (a+b) //2
        if liste[m] == element :
            return m
        elif liste[m] > element :
            b = m-1
        else :
            a = m+1

    return a

print (recherche(3, [3, 1, 4, 2, 3]))

TD01/code/rod-cutting.py

deleted100644 → 0
+0 −20
Original line number Diff line number Diff line
INT_MIN = 0

def cutRod(price, n): 

    # Initialisation tables de cache
    val = [0 for x in range(n+1)] 
    val[0] = 0
  
    for i in range(1, n+1): 
        max_val = INT_MIN 
        for j in range(i): 
             max_val = max(max_val, price[j] + val[i-j-1]) 
        val[i] = max_val 
  
    return val[n] 
  
if __name__=="__main__": 
    arr = [1, 5, 8, 9, 10, 17, 17, 20] 
    size = len(arr) 
    print("Valeur maximum de découpe " + str(cutRod(arr, size))) 
 No newline at end of file

TD01/code/set-duplicatas.py

deleted100644 → 0
+0 −11
Original line number Diff line number Diff line
def duplicatas(L):
	s = set()
	for x in L:
		if x in s:
			return True
		s.add(x)
	return False

if __name__=="__main__": 
	assert duplicatas([3, 5, 3]) == True
	assert duplicatas([3, 5, 5]) == False

TD01/code/set-exemples.py

deleted100644 → 0
+0 −59
Original line number Diff line number Diff line
{3,6,"cat",4.5,False}

# {False, 4.5, 3, 6, 'cat'}     # L'ensemble est ordonné
my_set = {3,6,"cat",4.5,False}
my_set

#{False, 3, 4.5, 6, 'cat'}

len(my_set)
# 5

False in my_set
# True

"dog" in my_set
#False

your_set =  {99,3,100}
my_set.union(your_set)
# {False, 3, 4.5, 6, 99, 'cat', 100}

my_set | your_set
# {False, 3, 4.5, 6, 99, 'cat', 100}

my_set.intersection(your_set)
# {3}

my_set & your_set
# {3}

my_set.difference(your_set)
# {False, 4.5, 6, 'cat'}

my_set - your_set
# {False, 4.5, 6, 'cat'}

{3,100}.issubset(your_set)
# True

{3,100} <= your_set
# True

my_set.add("house")
my_set
# {False, 3, 4.5, 6, 'house', 'cat'}

my_set.remove(4.5)
my_set
# {False, 3, 6, 'house', 'cat'}

my_set.pop()
# False

my_set
# {3, 6, 'house', 'cat'}

my_set.clear()
my_set
set()               # Ensemble vide
 No newline at end of file

TD01/code/tas.py

deleted100644 → 0
+0 −62
Original line number Diff line number Diff line
class Tas():
    def __init__(self):
        self.__values = []

    def push(self, value):
        self.__values.append(value)

    def peek(self, i): # pop sans suppression
        return self.__values[i], i
        
    def fg(self, i):
        left_i = 2 * i + 1
        if left_i > len(self.__values):
            return None, left_i
        else:
            return self.__values[left_i], left_i

    def fd(self, i):
        droite_i = 2 * i + 2
        if droite_i > len(self.__values):
            return None, droite_i
        else:
            return self.__values[droite_i], droite_i

    def parent(self, i):
        return self.__values[(i - 1) // 2]

    def afficher(self):
        return ' '.join(str(v) for v in self.__values)

    def inserer(self, value):
        self.push(value)
        i = len(self.__values) - 1
        while (i + 1) // 2 > 0:
            if self.__values[i] < self.parent(i):
                tmp = self.__values[i // 2]
                self.__values[i // 2] = self.__values[i]
                self.__values[i] = tmp
            i = i // 2
        
    def supprimer(self, i):

        v = self.__values.pop(i)
        max_i = i
        n = len(self.__values) - 1

        while self.__values[i] > self.fg(i)[0] or self.__values[i] > self.fd(i)[0]:

            max = self.__values[i]
            
            if i < n and max > self.fg(i)[0]:
                max_i = 2 * i + 1

            if i < n and max > self.fd(i)[0]:
                max_i = 2 * i + 2

            if max_i != i: 
                self.__values[i], self.__values[max_i] = self.__values[max_i], self.__values[i]

            i = max_i

        return v
 No newline at end of file

TD01/code/time.py

deleted100644 → 0
+0 −7
Original line number Diff line number Diff line
import timeit

print(timeit.timeit("x = 2 + 2"))
#.0188..............

print(timeit.timeit("x = range(10)"))
#.589.........

TD01/code/tirage-des.py

deleted100644 → 0
+0 −26
Original line number Diff line number Diff line
from random import *

effectifs=[0,0,0,0,0,0]
# OU 
# effectif=[0]*6
for n in range(10000):
    dice=randint(1,6)
    effectifs[dice-1]+=1

print(effectifs)

#--> [1642, 1710, 1683, 1661, 1678, 1626]
# Donner l'intervalle de confiance associé à ce résultat à 95%

#Même chose avec 2 dés
from random import *

effectifs=[0]*11
for n in range(10000):
    de1=randint(1,6)
    de2=randint(1,6)
    twodice=de1+de2
    effectifs[twodice-2]+=1

print(effectifs)
# --> [299, 540, 832, 1159, 1401, 1665, 1401, 1103, 787, 541, 272]
 No newline at end of file

TD01/code/tirage-gaussienne.py

deleted100644 → 0
+0 −24
Original line number Diff line number Diff line
from math import *
from random import *

def tirage_gauss_centre_reduit():
    x=uniform(0,1)
    y=sqrt(-2*log(uniform(0,1)))
    y = y*cos(x*2*pi)
    return y 
 
try :
  n=int(input("combien de valeurs : "))
  for i in range(n) :
    print("Le tirage : ", tirage_gauss_centre_reduit())
except ValueError as err :
  print("Error: {0}".format(err))    

""" TRACE :
combien de valeurs : 5
Le tirage :  0.1675459650607427
Le tirage :  -0.8810297798592189
Le tirage :  0.4764601603767129
Le tirage :  -1.8446292482050937
Le tirage :  -0.35483078367598453
"""
 No newline at end of file

TD01/code/tirage-random.py

deleted100644 → 0
+0 −19
Original line number Diff line number Diff line
# imports
from random import seed, random

# fonctions
def listAleatoireFloat(n):
    """Retourne une liste de <n> flottants aleatoires."""
    return [random() for i in range(n)]

# programme principal  
n = int(input("Entrez un entier [2 .. 100] : "))
while not (2 <= n <= 100): # saisie filtree
    n = int(input("Entrez un entier [2 .. 100], s.v.p. : "))

seed() # initialise le generateur de nombres aleatoires
t = listAleatoireFloat(n) # construction de la liste

print("Liste :", t)
print("Amplitude : {:.2f}".format(max(t) - min(t)))
print("Moyenne : {:.2f}".format(sum(t)/n))
 No newline at end of file

TD01/code/tirage-remise.py

deleted100644 → 0
+0 −26
Original line number Diff line number Diff line
from math import *
from random import *

# Simulation d'un tirage avec remise de k objets parmi n

def tirage_uniforme_k_of_n_avec_remise(n,k):
    if k > n :
        raise ValueError("k (%d) doit être =< que n (%d) " % (k,n))
    T=[x for x in range(1,n+1,1)]   # On constitue une urne avec p objets

    for i in range(k) : # Tirage de k numéros
            d=randint(1,n)
            # On permute le d-ème élément de l'urne et la derniere
            temp=T[d-1]
            T[d-1]=T[n-1]
            T[n-1]=temp
            n=n-1
    return T[n:n+k+1]
    

n=int(input("La valeur de n ? "))
k=int(input("La valeur de k (parmi n) ? "))
try :
    print("Le tirage : ", tirage_uniforme_k_of_n_avec_remise(n,k))
except ValueError as err :
    print("Error: {0}".format(err))
 No newline at end of file

TD01/code/tri-bulle.py

deleted100644 → 0
+0 −12
Original line number Diff line number Diff line
def tri_bulle_iteratif(lst):
    """ Tri par bulle """
    taille = len(lst)
    for i in range(taille-1) :
        for j in range(i+1,  taille) :
            if lst[i] > lst[j] :
                lst[i] , lst[j] = lst[j] , lst[i]   # permutaion
    return lst
    
liste=[1,3,13,4,7,2,9,2,18] 
print(tri_bulle_iteratif(liste))
# [1, 2, 2, 3, 4, 7, 9, 13, 18]
 No newline at end of file

TD01/code/tri-fusion.py

deleted100644 → 0
+0 −62
Original line number Diff line number Diff line
from random import seed, randint, shuffle

def tri_split_merge(L) :
    """ TRI SPLIT-MERGE avec 2 fonctions imbriquées """
    def my_split(L) :
        choix=True              # on met dans L1, sinon dans L2 
        L1=[]; L2=[] ; N =len(L)
        i=0
        while i < N :
            crt=L[i]
            if choix : L1.append(crt)
            else : L2.append(crt)
            i +=1
            # voyons si on a une séquence Descendante
            while i < N and L[i] >= crt :
                crt=L[i]
                if choix : L1.append(crt)
                else : L2.append(crt)
                i +=1
                
            choix = not choix
            
        return(L1,L2)
    
    #---------------------  
    def my_merge(L1,L2) :
        N1=len(L1)
        N2=len(L2)
        L=[]; i,j=0,0
        while(i < N1 and j < N2) :
            if L1[i] <= L2[j] : 
                L.append(L1[i]) 
                i+=1
            else :
                L.append(L2[j]) 
                j+=1
        L.extend(L1[i:])    # Ajouter le reste de L1 (s'il y en a) à L
        L.extend(L2[j:])    # Ajouter le reste de L2 (s'il y en a) à L
        return L
        
    # Fonction tri_split_merge
    while True :
        (L1,L2) = my_split(L)
        if (L2==[]) : break # Fini
        L=my_merge(L1,L2)  
    return L
        
# programme principal -----------------------------------------------
seed() # initialise le generateur de nombres aleatoires
N=10
L = [randint(2, N*4) for i in range(N)] # construction de la liste
print("Avant le tri, liste = {}".format(L))
L=tri_split_merge(L)
print("Après le tri, liste = {}".format(L))

""" Deux Traces
Avant le tri, liste = [9, 17, 12, 24, 36, 26, 35, 25, 5, 31]
Après le tri, liste = [5, 9, 12, 17, 24, 25, 26, 31, 35, 36]

Avant le tri, liste = [30, 14, 2, 11, 5, 15, 5, 21, 29, 31]
Après le tri, liste = [2, 5, 5, 11, 14, 15, 21, 29, 30, 31]
"""
 No newline at end of file

TD01/code/tri-insertion.py

deleted100644 → 0
+0 −34
Original line number Diff line number Diff line
from random import seed, randint

        
def tri_insertion_iter(T) :
    def inserer_a_sa_place_iter(ind) : # insere le Ieme dans T[0:i]
        save = T[ind]
        i=ind
        while (i>0 and T[i-1] > save) : 
            T[i]=T[i-1]
            i -= 1
        T[i]=save
        
    if len(T) < 2 : return
    for i in range(1,len(T)) :
        inserer_a_sa_place_iter(i)  # insere le Ieme dans T[0:i]
        
# ------- Prog Princ
seed()                                      # initialise le generateur de nombres aleatoires
N=10
T = [randint(2, 3*N) for i in range(N)]     # construction de la liste
print("Avant le tri, liste = {}".format(T))
TT=[]                                       # Avant d'utiliser TT, il faut la faire exister !
TT[:]=T[:]
tri_insertion_iter(T)
TT.sort()
if (T == TT) :
    print("Après le tri, liste = {}".format(T))
else :
    print("ERREUR !!, T={}, TT={}".format(T,TT)) 

""" TRACE :
Avant le tri, liste = [14, 11, 24, 24, 27, 14, 30, 22, 22, 17]
Après le tri, liste = [11, 14, 14, 17, 22, 22, 24, 24, 27, 30]
"""
 No newline at end of file

TD01/code/tri-rapide.py

deleted100644 → 0
+0 −17
Original line number Diff line number Diff line
def quicksort(t):
    if t == []:
        return []
    else:
        pivot = t[0]
    t1 = []
    t2 = []
    for x in t[1:]:
        print(x, pivot)
        if x < pivot:
            t1.append(x)
        else:
            t2.append(x)
        return quicksort(t1) + [pivot] + quicksort(t2)

if __name__=="__main__": 
    quicksort([1 ,4, 5])
 No newline at end of file

TD01/code/util-commentaires.py

deleted100644 → 0
+0 −15
Original line number Diff line number Diff line
# Un commentaire court commence par un # et se limite à la fin de la ligne

"""
On peut aussi créer un commentaire long = une zone de 
commentaires  sur plusieurs lignes placées
entre une paire de triple-guillements dont le second suit :
"""

# Remarques : 
# Un ';' à la fin d'une ligne rend la ligne muette (pas d'affichage des résultats). 
# Il permet également de placer plusieurs expressions sur la même ligne.

# Si vous placez un commentaire immédiatement après la signature d'une fonction} 
# (ou une méthode, une classe, etc.) entre un couple de  """, 
# votre commentaire (appelé docstring) devient accessible avec help
 No newline at end of file
+0 −141
Original line number Diff line number Diff line
# 8 Conversion de types

list1 = ['1', '2', '3']
str1 = ''.join(list1)

str1
# '123'

list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)   # ou avec "" à la place de ''

str1
# '123'


a = "545.2222"
float(a)
# 545.2222      suivant le système, on peut avoir des '0' après les '2'

int(float(a))
# 545

def is_float(value):
  try:
    float(value)
    return True
  except:
    return False

# On peut aussi utiliser la prédéfinie eval() qui évalue du code Python
eval("1.5") 
# 1.5

# Une alternative plus sûre à eval()
import ast
ast.literal_eval("545.2222")
545.2222

ast.literal_eval("31")
31

# Des cas d'erreur 
eval(toto)          # toto non défini ou n'est pas un str/octes/code
ast.literal_eval(toto)
# Erreur dans les 2 cas


# Converstion en binaire
st = "hello Debase"
' '.join(format(ord(x), 'b') for x in st)
# '1101000 1100101 1101100 1101100 1101111 100000 1000100 1100101 1100010 1100001 1110011 1100101'

# Conversion de string en hexadécimal
s='Hello Debase of Ecl'
' '.join(format(ord(x), 'x') for x in s)
# '48 65 6c 6c 6f 20 44 65 62 61 73 65 20 6f 66 20 45 63 6c'

# Conversion entier en Unicode
chr(16)     # Quelle est la forme hexa de 16 ?
#'\x10'

# Conversions décimal <==> base xx

int('12',8) # Quelle est la valeur décimale du nombre octal '12' (octal car base = 8)
# 10    

int('12',16) # Quelle est la valeur décimale du nombre hexa '12' (hexa car base = 16)
# 18

int('12')   # Quelle est la valeur décimale du nombre décimale '12' (décimal car base par défaut = 10)
# 12

int('1000',2)   # Que donne le nombre binaire '1000' en décimal (binaire car base = 2)
# 8   

# Pour convertir un entier en octal

oct(12)
# '0o14'        #un 'O' au début (pour Octal)

oct(8)
# '0o10'

# Autres conversions

# octal
eval('0o010') == 10     # La valeur décimale de '0o010' est-elle 10
# False

eval('0o010')
# 8

oct(42)               # La valeur octale de l'entier 42
# '0o52'

int('0o52', 0)      # La valeur décimale de l'octale  '0o52' (si base=0 alors base est dans le string)
# 42

int('1101', 2)      # La valeur décimale du binaire '1101'  (base explicite = 2)
#13

int('0b1101', 2)    # Idem, base explicitée = 2, peut importe '0b'
#13

int('0b1101', 0)    # La valeur décimale du binaire '0b1101' (base = 0 --> la base '0b' est dans le string)
#13

from struct import *

pack('hhl', 1, 2, 3)
# b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'
# b veut dire byte (2 octes). \x veut dire hexa

pack('b', 1)
# b'\x01'

pack('b', 16) # signed char de taille 1. On convertie 16 en signed char
# b'\x10' 

In [39]: pack('B', 16)  # unsigned char de taille 1
# b'\x10'

pack('h', 1)
# b'\x01\x00'

calcsize('h')
# 2

calcsize('b')
# 1

unpack('b', b'\x10')
# (16,)

type(unpack('b', b'\x10'))
# tuple

unpack('b', b'\x10')[0]    # Première élé. Il y a virgule car taille tuple >= 2  
# 16

pack('B',65) # donne b'A'   = i.e. le caractère dont le code = 65
 No newline at end of file

TD01/code/util-types.py

deleted100644 → 0
+0 −39
Original line number Diff line number Diff line
# 7 Types principaux en Python

if type(1) is not int : print('oups')

if type('1') is not int : print(1)

type(3.14)
# float

type(None)
# NoneType

f = lambda c : c if type(c) is str and  c.isalpha() else '?'
type(f)
# function

# Utilisation de f (voir plus loin les "lambda expressions") :
f('a')  # donne 'a' car 'a' est alphabétique
f('1')  # donne '?' car '1' n'est  pas alphabétique
f(1)    # donne '?'  car  1 n'est  pas une chaine

import sys;

print(sys.int_info)
# sys.int_info(bits_per_digit=30, sizeof_digit=4)

print(sys.float_info)
# sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308,
# min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15,
# mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

print(sys.getsizeof(float))     # La taille de  la classe float
# 400
print(sys.getsizeof(float()))   # La taille d'un  float
# 24                            # Ce que coute en octes un réel 
                                # (valeur  + infos supplémentaires)


TD01/code/util-version-python.py

deleted100644 → 0
+0 −9
Original line number Diff line number Diff line
# Vous devez valider ce code qui affiche le numéro de version
# Rien d'autre à faire !
import sys

if not sys.version_info.major == 3 and sys.version_info.minor >= 7:
    print("Python 3.7 ou supérieur est nécessaire !")
else:
    print("Vous utilisez {}.{}.".format(sys.version_info.major, sys.version_info.minor))
    sys.exit(1)
 No newline at end of file

TD01/code/zip-codes-romain.py

deleted100644 → 0
+0 −14
Original line number Diff line number Diff line
code = zip([1000,900 ,500,400 ,100,90 ,50 ,40 ,10 ,9 ,5 ,4 ,1], ["M" ,"CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"])

# fonctions
def zipConversionRomain(num):
    res = []
    for d, r in code:
        while num >= d:
            res.append(r)
            num -= d
    return ''.join(res)

# programme principal -----------------------------------------------
for i in range(1, 15):
    print(i, zipConversionRomain(i))
 No newline at end of file
+1362 −0

File added.

Preview size limit exceeded, changes collapsed.

TD02/code/load.py

deleted100644 → 0
+0 −12
Original line number Diff line number Diff line
data = []

with open("etudiants.txt") as f:
    keys = None
    for line in f:
        l = [w.strip() for w in line.split(';')]
        if keys is None:
            keys = l
        else:
            data.append(l)

print(data)
 No newline at end of file

TD02/code/test_analyse.py

deleted100644 → 0
+0 −28
Original line number Diff line number Diff line
#%%
import time
import random
import matplotlib.pyplot as plt
import numpy as np
#%matplotlib inline

nvalues = [100, 500, 1000, 1500, 2000, 2500, 3000]
timesEtudiants1 = []

for i in nvalues:

    random.seed()
    p = 12**2 # Ordre de grandeur des valeurs
    liste = []
    
    for x in range(i): liste.append(random.randint(0, p))

    a=time.perf_counter()
    e1 = []
    for n in liste:
        e1.append(n)
    b=time.perf_counter()
    timesEtudiants1.append(b-a)

plt.plot(nvalues,timesEtudiants1, "r-", label="Etudiants 1")
plt.title("Comparaison des performances")
# %%

TD02/code/test_file.py

deleted100644 → 0
+0 −23
Original line number Diff line number Diff line
from File import *

if __name__=="__main__": 

    data = []

    with open("etudiants.txt") as f:
        keys = None
        for line in f:
            l = [w.strip() for w in line.split(';')]
            if keys is None:
                keys = l
            else:
                data.append({k:v for k, v in zip(keys, l)})
                
    file = File()

    for d in data:
        file.ajoute(d)

    e = file.renvoie(lambda x : x['filiere'] == "PC")

    print(e['nom'] + " " + e['prenom'])
 No newline at end of file

TD02/code/test_heap.py

deleted100644 → 0
+0 −9
Original line number Diff line number Diff line
import heapq
tas = []

for i in range(5): heapq.heappush(tas, i)

while not len(tas) == 0: 
  print(heapq.heappop(tas), end=" ")

# 0 1 2 3 4
 No newline at end of file

TD02/code/test_lifoqueue.py

deleted100644 → 0
+0 −9
Original line number Diff line number Diff line
import queue
pile = queue.LifoQueue()

for i in range(5): pile.put(i)

while not pile.empty(): 
  print(pile.get(), end=" ")

# 4 3 2 1 0
 No newline at end of file

TD02/code/test_pile.py

deleted100644 → 0
+0 −21
Original line number Diff line number Diff line
from Pile import *

if __name__=="__main__": 

    data = []

    with open("etudiants.txt") as f:
        keys = None
        for line in f:
            l = [w.strip() for w in line.split(';')]
            if keys is None:
                keys = l
            else:
                data.append({k:v for k, v in zip(keys, l)})
                
    p = Pile()
    for d in data:
        p.ajoute(d)
 
    e = p.supprime()
    assert(e['nom'] == "Arthaud" and e['prenom'] == "Nathalie") 
 No newline at end of file

TD02/code/test_tas.py

deleted100644 → 0
+0 −26
Original line number Diff line number Diff line
from Tas import *

if __name__=="__main__": 
        
    data = []

    with open("etudiants.txt") as f:
        keys = None
        for line in f:
            l = [w.strip() for w in line.split(';')]
            if keys is None:
                keys = l
            else:
                data.append({k:v for k, v in zip(keys, l)})

    tas = Tas()

    for d in data:
        tas.ajoute(int(d['moyenne']))
    
    r = tas.get_racine()
    fg, fg_i = tas.get_fils_gauche(0)
    ffg, ffg_i = tas.get_fils_droit(0)

    assert(r == 19 and fg == 14 and ffg == 16) 
   
 No newline at end of file
+101 −0
Original line number Diff line number Diff line
nom;prenom;filiere;moyenne;absences
Dickerson;Chaney;PSI;6;4
King;Shay;PSI;2;2
Chan;Aileen;MP;8;3
Schwartz;Destiny;PSI;16;5
Parrish;Prescott;MP;1;4
Calhoun;Brenda;PSI;10;4
Watts;Shellie;PSI;6;4
Baird;Octavius;PC;4;2
Graves;Vanna;MP;10;0
Decker;Nerea;PSI;9;4
Townsend;Naomi;PC;13;3
Decker;Nichole;PSI;10;3
Mcgee;Blythe;PSI;7;0
Franco;Cyrus;PSI;12;1
Mcdowell;Zelda;MP;6;1
Cherry;Stone;PSI;10;5
Mendoza;Kirsten;PC;18;0
Mathis;Xaviera;MP;12;1
Booker;Gretchen;MP;2;1
Hansen;Slade;PSI;1;1
Mason;Forrest;MP;13;3
Wolfe;Fatima;PC;15;5
Richards;Justine;MP;20;0
Kelley;Abra;PC;2;4
Lang;Ulysses;PSI;2;5
Barker;Austin;MP;15;5
Cannon;Kalia;MP;3;4
Higgins;Charity;PSI;18;5
Parker;Fritz;PC;14;2
Chambers;Yvette;PSI;7;1
Vinson;Denise;PSI;3;5
Mcmillan;Chava;PSI;7;3
Gallegos;Lee;PC;16;0
Ferguson;Solomon;PSI;11;4
Camacho;Zena;MP;4;4
Sexton;Fallon;PSI;16;2
Campbell;Preston;PC;0;0
Greer;Lance;PC;15;5
Oliver;Aileen;PC;10;2
Nielsen;Timon;PC;1;2
Perkins;Roth;PSI;1;2
Beard;Blair;PSI;13;1
Burgess;Keely;PSI;4;4
Wells;Honorato;PSI;17;0
Richardson;Cherokee;PC;20;1
Burgess;Blair;PC;16;4
Rice;Florence;PC;7;4
Villarreal;Delilah;MP;9;5
Cherry;Maite;MP;0;2
Berry;Jermaine;MP;17;4
Shepherd;Alfreda;PSI;20;5
Workman;April;PC;3;1
Carter;Herman;PC;11;1
Carpenter;Teagan;MP;0;1
Fowler;Leo;PSI;19;4
Mcgee;Kristen;PSI;9;4
Mcpherson;Channing;PC;0;0
Diaz;Nathaniel;PC;4;5
Klein;Maisie;PSI;16;3
Graham;Gary;MP;12;4
Jensen;Raja;PC;18;1
Wilkinson;Sawyer;PSI;10;0
Wagner;Lamar;MP;16;2
Abbott;Sybil;MP;17;1
Glenn;Arsenio;PSI;4;3
Moreno;Axel;PSI;7;4
Barrett;Dylan;PC;14;4
Keith;Rae;PC;9;1
Shepard;Rebecca;PC;8;5
Meyers;Illiana;MP;3;3
Bruce;Tatyana;MP;2;0
Mcguire;Olivia;PC;17;4
Merritt;Tatiana;PSI;19;3
Berg;Dale;MP;12;1
Matthews;Tallulah;MP;5;3
Steele;Cain;MP;8;2
Ellison;Britanni;PC;4;1
Richards;Audra;MP;15;0
Hood;Rylee;PSI;1;4
Townsend;Paul;PC;14;4
Cervantes;Thaddeus;MP;10;5
Dudley;Amela;PC;2;0
Lucas;Matthew;MP;4;1
Parrish;Nell;PC;13;3
Patterson;Bertha;PSI;18;0
Knapp;Lawrence;MP;3;5
Stanton;Keith;MP;5;2
Hayes;Mannix;PSI;3;2
Pearson;Ross;PC;10;4
Kaufman;Uta;MP;10;4
Bauer;Naida;PC;20;5
Carrillo;Quamar;PC;15;3
Orr;Lisandra;PSI;6;2
Randolph;Darryl;PSI;16;4
Boyer;Prescott;PC;20;2
Serrano;Ashely;PSI;10;2
Carney;Oren;PC;7;4
Riley;Arden;PC;1;5
Phillips;Joshua;PSI;20;3
Soto;Colt;PC;16;3
 No newline at end of file
Original line number Diff line number Diff line
nom;prenom;filiere;moyenne;absences
Dupond;Pierre;MP;19;0
nom;prenom;filiere;note;absences
Dupond;Pierre;MP;19;7
Dupont;Jeanne;MP;19;5
Clavier;Christian;PSI;14;1
Gilles;Eric;PC;16;3
Arthaud;Nathalie;MP;15;0
 No newline at end of file
+896 −0

File added.

Preview size limit exceeded, changes collapsed.

TD03/code/viz.py

deleted100644 → 0
+0 −11
Original line number Diff line number Diff line
from graphviz import Digraph

g = Digraph('G', filename='graph.gv')

g.edge('a', 'b')
g.edge('a', 'c')

print(g.source)

g.render(filename='img')
g.view()
 No newline at end of file
+1025 −0

File added.

Preview size limit exceeded, changes collapsed.

TD04/code/load.py

deleted100644 → 0
+0 −14
Original line number Diff line number Diff line
labyrinthe = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

def affiche_labyrinthe(l):
    print('\n'.join([''.join(['{:4}'.format(item) for item in row]) 
        for row in l]))
 No newline at end of file

TD04/code/priorite.py

deleted100644 → 0
+0 −9
Original line number Diff line number Diff line
from queue import PriorityQueue

file_prio = PriorityQueue()
file_prio.put((2, "Bob"))
file_prio.put((1, "Alice"))
file_prio.put((6, "Nat"))

while not file_prio.empty():
     print(file_prio.get()[1])
 No newline at end of file
+214 −0

File added.

Preview size limit exceeded, changes collapsed.

+780 −0

File added.

Preview size limit exceeded, changes collapsed.

TD06/mots-10.txt

0 → 100755
+10 −0
Original line number Diff line number Diff line
a
à
abaissa
abaissable
abaissables
abaissai
abaissaient
abaissais
abaissait
abaissâmes
 No newline at end of file