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

Mise à jour exemples de code

parent 9289a0f8
Branches
No related tags found
No related merge requests found
# 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
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
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
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
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
......@@ -6,10 +6,12 @@ def quicksort(t):
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
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+=1
k+=1
while j < len(R):
arr[k] = R[j]
j+=1
k+=1
\ No newline at end of file
# 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
File moved
File moved
File moved
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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment