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
147 files
+ 344733
2377
Compare changes
  • Side-by-side
  • Inline

Files

+27 −0
Original line number Original line Diff line number Diff line
# INF-TC1
# 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 Original line Diff line number Diff line

TD01/code/arbre-k-aire.py

deleted100644 → 0
+0 −56
Original line number Original line Diff line number Diff line
import sys

class Noeud:
    def __init__(self, v, c = []):
        self.v = v
        self.c = c

def parcours_affiche(arbre):
    for c in arbre.c:
        parcours_affiche(c)

    print(arbre.v)


def parcours_recherche(arbre, valeur):

    if arbre is None:
        return False

    stack = arbre.c

    if valeur > arbre.v:
        return False

    if valeur == arbre.v:
        return True

    prev = sys.maxsize

    while len(stack) > 0:
        children = stack.pop(0)
        if valeur == children.v:
            return True
        if valeur > prev and valeur < children.v:
            stack = children.c
            prev = stack[0].v
        else:
            prev = children.v

    return False

if __name__=="__main__": 

    racine = Noeud(13, [Noeud(4, [Noeud(1), Noeud(2), Noeud(3)]), Noeud(8, \
    [Noeud(5), Noeud(6), Noeud(7)]),  Noeud(12, [Noeud(9), Noeud(10), Noeud(11)])])

    print(parcours_affiche(racine))

    # renvoie False pour un arbre vide
    parcours_recherche(None, -1)

    # 11 est dans l'arbre
    assert parcours_recherche(racine, 11) == True

    # 12 n'est pas dans l'arbre
    assert parcours_recherche(racine, 12) == False
 No newline at end of file
+0 −35
Original line number Original line Diff line number Diff line
class Noeud:
    def __init__(self, v, c = []):
        self.v = v
        self.c = c

def parcours(n):
    stack = []
    stack.append(n)
    r = []
    while len(stack) > 0:
        current = stack.pop(0)
        r.append(current.v)
        for v in current.c:
            stack.append(v)
    return r

if __name__=="__main__": 

    print(parcours(Noeud(1,                         \
                    [                               \
                        Noeud(2, [                  \
                            Noeud(4), Noeud(5)      \
                        ]),                         \
                        Noeud(3)                    \
                    ]                               \
                )                                   \
    ))

    # [1, 2, 3, 4, 5]
    print(parcours(Noeud(5, [Noeud(4, [Noeud(2), Noeud(1)]), Noeud(3)])))
    # [5, 4, 3, 1, 2]
    print(parcours(Noeud(5, [Noeud(1), Noeud(2), Noeud(3), Noeud(4)])))
    # [5, 1, 2, 3, 4]
    print(parcours(Noeud(1, [Noeud(5), Noeud(4), Noeud(3), Noeud(2)])))
    # [1, 5, 4, 3, 2]
+0 −80
Original line number Original line Diff line number Diff line
class Noeud:
    def __init__(self, v, c = []):
        self.v = v
        self.c = c

def parcour_largeur(n):

    stack = []
    stack.append(n)

    while len(stack) > 0:
        current = stack.pop(0)

        for s in current.c:
            stack.append(s)

        print(current.v)

def parcour_largeur(n):

    stack = []
    stack.append(n)

    while len(stack) > 0:
        current = stack.pop(0)

        for s in current.c:
            stack.append(s)

        print(current.v)

def parcour_profondeur(n):

    stack = []
    stack.append(n)

    while len(stack) > 0:
        current = stack.pop()

        for s in reversed(current.c):
            stack.append(s)

        print(current.v)

def parcour_profondeur_rec(n):

    if len(n.c) > 0:
        parcour_profondeur_rec(n.c[0])

    print(n.v)

    if len(n.c) > 1:
        parcour_profondeur_rec(n.c[1])

def parcour_profondeur_rec_dic(n, A):

    if len(A[n]) > 0:
        parcour_profondeur_rec_dic(A[n][0], A)

    print(n)

    if len(A[n]) > 1:
        parcour_profondeur_rec_dic(A[n][1], A)


racine = Noeud("chien", [Noeud("petit", [Noeud("le")]), Noeud("et", [Noeud("jaune"), Noeud("noir")])])

parcour_profondeur_rec(racine)

A = {"chien": ["petit", "et"],
    "petit": ["le"],
    "le": [],
    "et": ["jaune", "noir"],
    "jaune": [],
    "noir": []
}

parcour_profondeur_rec_dic("chien", A)

print(A.keys())
 No newline at end of file

TD01/code/arbre-tuple.py

deleted100644 → 0
+0 −56
Original line number Original line Diff line number Diff line
import sys

class Noeud:
    def __init__(self, v, c = []):
        self.v = v
        self.c = c

def parcours_affiche(arbre):
    for c in arbre.c:
        parcours_affiche(c)

    print(arbre.v)


def parcours_recherche(arbre, valeur):

    if arbre is None:
        return False

    stack = arbre.c

    if valeur > arbre.v:
        return False

    if valeur == arbre.v:
        return True

    prev = sys.maxsize

    while len(stack) > 0:
        children = stack.pop(0)
        if valeur == children.v:
            return True
        if valeur > prev and valeur < children.v:
            stack = children.c
            prev = stack[0].v
        else:
            prev = children.v

    return False    

if __name__=="__main__": 

    racine = Noeud(13, [Noeud(4, [Noeud(1), Noeud(2), Noeud(3)]), Noeud(8, \
    [Noeud(5), Noeud(6), Noeud(7)]),  Noeud(12, [Noeud(9), Noeud(10), Noeud(11)])])

    print(parcours_affiche(racine))

    # renvoie False pour un arbre vide
    parcours_recherche(None, -1)

    # 11 est dans l'arbre
    assert parcours_recherche(racine, 11) == True

    # 12 n'est pas dans l'arbre
    assert parcours_recherche(racine, 12) == False
 No newline at end of file

TD01/code/bfs-tree.py

deleted100644 → 0
+0 −30
Original line number Original line Diff line number Diff line
import collections

class graph:
    def __init__(self,gdict=None):
        if gdict is None:
            gdict = {}
        self.gdict = gdict

def bfs(graph, startnode):
    seen, queue = set([startnode]), collections.deque([startnode])
    while queue:
        vertex = queue.popleft()
        marked(vertex)
        for node in graph[vertex]:
            if node not in seen:
                seen.add(node)
                queue.append(node)

def marked(n):
    print(n)

tree = { "a" : set(["b","c"]),
                "b" : set(["e", "d"]),
                "c" : set(["f"]),
                "f" : set(["i"]),
                "e" : set(["g", "h"]),
                "d" : set(), "i" : set(), "g" : set(), "h" : set() 
                }

bfs(tree, "a")
 No newline at end of file

TD01/code/bfs.py

deleted100644 → 0
+0 −32
Original line number Original line Diff line number Diff line
import collections

class graph:
    def __init__(self,gdict=None):
        if gdict is None:
            gdict = {}
        self.gdict = gdict

def bfs(graph, startnode):
# Track the visited and unvisited nodes using queue
        seen, queue = set([startnode]), collections.deque([startnode])
        while queue:
            vertex = queue.popleft()
            marked(vertex)
            for node in graph[vertex]:
                if node not in seen:
                    seen.add(node)
                    queue.append(node)

def marked(n):
    print(n)

if __name__=="__main__": 

    gdict = { "a" : set(["b","c"]),
                    "b" : set(["a", "d"]),
                    "c" : set(["a", "d"]),
                    "d" : set(["e"]),
                    "e" : set(["a"])
                    }

    bfs(gdict, "a")
 No newline at end of file

TD01/code/chaines-valide.py

deleted100644 → 0
+0 −10
Original line number Original line 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 Original line 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 −9
Original line number Original line 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 Original line 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/dfs-arbre.py

deleted100644 → 0
+0 −17
Original line number Original line Diff line number Diff line
def dfs(graph, start):
    visited, stack = set(), [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

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

dfs(graph, 'A') # {'E', 'D', 'F', 'A', 'C', 'B'}
 No newline at end of file

TD01/code/dict.py

deleted100644 → 0
+0 −62
Original line number Original line 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/exceptions.py

deleted100644 → 0
+0 −33
Original line number Original line 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-mem.py

deleted100644 → 0
+0 −18
Original line number Original line 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] 

if __name__=="__main__": 
    n = 6 
    max = 100
    lookup = [None]*(max) # initialise la table de cache
    print("Le nombre de fibonacci est ", fib(n, lookup)) # affiche 8
 No newline at end of file

TD01/code/fibo-rec.py

deleted100644 → 0
+0 −11
Original line number Original line Diff line number Diff line
def fibo(n):
   if n <= 1:
       return n
   else:
       return(fibo(n-1) + fibo(n-2))

if __name__=="__main__": 
    n = 10
    print("Séquence de Fibonacci de {} nombres :".format(n))
    for i in range(10):
        print(fibo(i))
 No newline at end of file

TD01/code/file.py

deleted100644 → 0
+0 −31
Original line number Original line 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/graph-check-color.py

deleted100644 → 0
+0 −38
Original line number Original line Diff line number Diff line
class Node:
    def __init__(self, v = None, n = []):
        self.v = v
        self.n = n
        self.visited = False

def verifier(r):
   
    stack = [r]
   
    while len(stack) > 0:
        c = stack.pop(0)
        for n in c.n:
            if(c.v == n.v): # meme couleur
                print("deux voisins de meme couleur")
                return False
            if not n.visited:
                stack.append(n)
                n.visited = True                

    return True

if __name__=="__main__": 
    n1 = Node("gray")
    n2 = Node("black")
    n3 = Node("gray")
    n4 = Node("gray")
    n5 = Node("black")
    n6 = Node("gray")

    n1.n = [n2]
    n2.n = [n1, n3, n4]
    n3.n = [n2, n5]
    n4.n = [n2, n5]
    n5.n = [n3, n4, n6]
    n6.n = [n5]

    print(verifier(n1)) # True
 No newline at end of file

TD01/code/graph-cycle.py

deleted100644 → 0
+0 −26
Original line number Original line Diff line number Diff line
graph = { 0 : [1], 1 : [2], 2 : [3], 3 : [4], 4 : [1] }
# https://algocoding.wordpress.com/2015/04/02/detecting-cycles-in-a-directed-graph-with-dfs-python/
def cycle_existe(G):                    
    color = { u : "white" for u in G  }  # Noeuds tous blancs
    trouve_cycle = [False]                 
 
    for u in G:                          # On visite tous les noeuds
        if color[u] == "white":
            dfs_visite(G, u, color, trouve_cycle)
        if trouve_cycle[0]:
            break
    return trouve_cycle[0]
 
def dfs_visite(G, u, color, trouve_cycle):
    if trouve_cycle[0]:                         
        return
    color[u] = "gray"                  
    for v in G[u]:                             
        if color[v] == "gray":                 
            trouve_cycle[0] = True       
            return
        if color[v] == "white":                
            dfs_visite(G, v, color, trouve_cycle)
    color[u] = "black"   

print(cycle_existe(graph))
 No newline at end of file

TD01/code/graph-get.py

deleted100644 → 0
+0 −25
Original line number Original line Diff line number Diff line
graph = { "a" : ["c"],
          "b" : ["c", "e"],
          "c" : ["a", "b", "d", "e"],
          "d" : ["c"],
          "e" : ["c", "b"],
          "f" : []
}


def genere_arretes(graph):
    edges = []
    for node in graph:
        for neighbour in graph[node]:
            edges.append((node, neighbour))

    return edges

# Affiche les sommets
print(list(graph.keys()))

# Affiche les arrêtes
print(genere_aretes(graph))

# >>> [('a', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('c', 'e'), 
#    ('b', 'c'), ('b', 'e'), ('e', 'c'), ('e', 'b'), ('d', 'c')]
 No newline at end of file

TD01/code/graph-labyrinthe.py

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

def affiche_labyrinthe (l):
    print('\n'.join(''.join('#' if item else '.' for item in row) for row in l))
    print()

def voisins(l, x, y):
    return ((x+dx, y+dy)
        for dx, dy in ((-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1))
        if 0 <= x+dx < len(l[0]) and 0 <= y+dy < len(l) and l[y+dy][x+dx] == 0)

# IMPORTANT : chaque appel récursif ne doit pas modifier les chemins des autres,
# donc chacun a une copie non modifiable du chemin, ce pourquoi on utilise un tuple plutôt que liste
def existe_profondeur(l, x0=0, y0=0, chemin=()):
    # print(x0, y0)
    if (x0, y0) == (len(l[0])-1, len(l)-1): # condition de terminaison
        return True
    chemin += ((x0, y0),) # on crée un nouveau chemin avec la position courante
    for x, y in voisins(l, x0, y0):
        if (x, y) in chemin: # on ignore le voisin si déjà visité par le chemin courant
            continue
        if existe_profondeur(l, x, y, chemin): # appel récursif à partir de la position voisine
            return True # on a trouvé un chemin par la position voisine, donc aussi par l'actuelle
    return False # aucun des voisins ne mène à la sortie, donc l'actuelle non plus

affiche_labyrinthe(labyrinthe)
print(existe_profondeur(labyrinthe))
+0 −20
Original line number Original line Diff line number Diff line
def BellmanFord(self, src): 

    # Distances infinies
    dist = [float("Inf")] * self.V 
    dist[src] = 0 

    # Relache les sommets - 1
    for i in range(self.V - 1): 
 
        # Met a jour noeud et parents
         for u, v, w in self.graph: 
            if dist[u] != float("Inf") and dist[u] + w < dist[v]: 
                    dist[v] = dist[u] + w 

    # Verifie si cycle
    for u, v, w in self.graph: 
            if dist[u] != float("Inf") and dist[u] + w < dist[v]: 
                    print "Le graphe contient des cycles négatifs"
                    return
    
 No newline at end of file