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
Showing
with 0 additions and 496 deletions
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
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))
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
# 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']
}
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
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 ?")
class Graphe:
def __init__(self, *args):
self.edges = [e for e in args]
self.nodes = []
for e in self.edges:
if e[0] not in self.nodes:
self.nodes += [ e[0] ]
if e[1] not in self.nodes:
self.nodes += [ e[1] ]
def mat(self):
self.mat = [[ 0 for j in range(len(self.nodes))] for i in range(len(self.nodes))]
for i in self.edges:
self.mat[ self.nodes.index(i[0]) ][ self.nodes.index(i[1]) ] = 1
self.mat[ self.nodes.index(i[1]) ][ self.nodes.index(i[0]) ] = 1
return self.mat
if __name__ == "__main__":
G = Graphe( ('A','B') , ('A','C') , ('B','C') )
print( 'Les noeuds de G sont : {}'.format(G.nodes) )
print( 'Les arêtes de G sont : {}'.format(G.edges) )
print( 'La matrice d\'adjacence de G est : {}'.format(G.mat()) )
\ No newline at end of file
# Création d'un matrice d'adjacence pour un graphe
n = 5
G = [[0 for j in range(n)] for i in range (n)]
# Ajout d'un lien (si le graphe est non orienté)
G[0][1] = 1
G[1][0] = 1
# Affichage du graphe
for row in G:
print(row)
\ No newline at end of file
# 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
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
def fusion(l1, l2):
res = []
i = 0
j = 0
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
res.append(l1[i])
i += 1
else:
res.append(l2[i])
j += 1
while i < len(l1):
res.append(l1[i])
i += 1
while j < len(l2):
res.append(l2[j])
j += 1
return res
print(fusion([2, 2, 3], [0, 4, 5, 14, 20, 25]))
# [0, 2, 2, 3, 4, 5, 14, 20, 25]
\ No newline at end of file
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
from LinkedList import *
ll = LinkedList() # 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
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
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")
# 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)
def mult(a, b):
if(b == 1):
return a
else:
return a + mult(a, b-1)
print(10 * 13, mult(10, 13))
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
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
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