Skip to content
Snippets Groups Projects
Commit 088e24ff authored by Romain Vuillemot's avatar Romain Vuillemot
Browse files

Nettoyage

parent b5a9c00f
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 621 deletions
File deleted
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
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]
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
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
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 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
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
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)
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
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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment