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

Target

Select target project
  • rvuillem/inf-tc1
  • hwei/inf-tc1
  • nmbengue/inf-tc1
  • fernanda/inf-tc1
  • mleger/inf-tc1
  • lmeng/inf-tc1
  • gferryla/inf-tc1
  • jconso/inf-tc1
  • smaghsou/inf-tc1
  • emarquet/inf-tc1
  • ecluzel/inf-tc1
  • aaudeoud/inf-tc1
  • tsegond/inf-tc1
  • aetienne/inf-tc1
  • djoly/inf-tc1
  • bcampeas/inf-tc1
  • dnovarez/inf-tc1
  • ruetm/inf-tc1
  • cchenu/inf-tc1
  • cguiotdu/inf-tc1
  • mclouard/inf-tc1
  • gwachowi/inf-tc1
  • qbaalaou/inf-tc1
  • sbrocas/inf-tc1
  • ppupion/inf-tc1
  • kinty/inf-tc1
  • hadomo/inf-tc1
  • tgicquel/inf-tc1
  • rhahn/inf-tc1
  • cguyau/inf-tc1
  • mpairaul/inf-tc1
  • rmuller/inf-tc1
  • rlecharp/inf-tc1
  • asebasty/inf-tc1
  • qmaler/inf-tc1
  • aoussaid/inf-tc1
  • kcherigu/inf-tc1
  • sgu/inf-tc1
  • malcalat/inf-tc1
  • afalourd/inf-tc1
  • phugues/inf-tc1
  • lsteunou/inf-tc1
  • llauschk/inf-tc1
  • langloia/inf-tc1
  • aboucard/inf-tc1
  • wmellali/inf-tc1
  • ifaraidi/inf-tc1
  • lir/inf-tc1
  • ynedjar/inf-tc1
  • schneidl/inf-tc1
  • zprandi/inf-tc1
  • acoradid/inf-tc1
  • amarcq/inf-tc1
  • dcombet/inf-tc1
  • gplaud/inf-tc1
  • mkernoaj/inf-tc1
  • gbichot/inf-tc1
  • tdutille/inf-tc1
58 results
Select Git revision
Show changes
Commits on Source (102)
Showing
with 27 additions and 467 deletions
# 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
File added
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):
stack = arbre.c
if valeur > arbre.v:
return False
if valeur == arbre.v:
return True
prev = stack[0].v
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
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))
print(parcours_recherche(racine, 11))
\ No newline at end of file
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
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
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")
# 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
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]
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
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
# 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
# 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é")
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
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
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)
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
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
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
class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)
self.distances = {}
def add_node(self, value):
self.nodes.add(value)
def add_edge(self, from_node, to_node, distance):
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.distances[(from_node, to_node)] = distance
def dijsktra(graph, initial):
visited = {initial: 0}
path = {}
nodes = set(graph.nodes)
while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
if min_node is None:
break
nodes.remove(min_node)
current_weight = visited[min_node]
for edge in graph.edges[min_node]:
weight = current_weight + graph.distance[(min_node, edge)]
if edge not in visited or weight < visited[edge]:
visited[edge] = weight
path[edge] = min_node
return visited, path
\ No newline at end of file