Browse Source

Arreglos de indentacion y debug de quicksort. Modificacion al modulo de prueba.

root 1 year ago
parent
commit
a2f5b8580e
5 changed files with 142 additions and 79 deletions
  1. BIN
      __pycache__/sorting.cpython-38.pyc
  2. 68
    61
      sorting.py
  3. 64
    9
      test_sortAlgo.py
  4. BIN
      utils/__pycache__/qsortUtils.cpython-38.pyc
  5. 10
    9
      utils/qsortUtils.py

BIN
__pycache__/sorting.cpython-38.pyc View File


+ 68
- 61
sorting.py View File

@@ -15,7 +15,8 @@ def mergeSort(lista):
15 15
 	# If the size of the list is greater than 1 then it enters here
16 16
 	if len(lista) > 1:
17 17
 		# Gets the half of the list
18
-		Midd = len(lista) / 2
18
+		Midd = len(lista) // 2
19
+
19 20
 		# Takes only the elements that are in the left of the list
20 21
 		Left = lista[Midd:]
21 22
 		# If the size of left still is not 1 then
@@ -30,35 +31,35 @@ def mergeSort(lista):
30 31
 			mergeSort(Right)
31 32
 
32 33
 		# Variables define for while and getting space in the list
33
-        i = j = k = 0
34
+		i = j = k = 0
34 35
 
35 36
 		# While i and j are less than the comparation it enters here
36
-        while i < len(Left) and j < len(Right):
37
+		while i < len(Left) and j < len(Right):
37 38
 			# If the compared number in i is less than j it enters here
38
-            if Left[i] < Right[j]:
39
+			if Left[i] < Right[j]:
39 40
 				# The less variable is stored in the list again in order
40
-                lista[k] = Left[i]
41
-                i += 1 # Increments i
41
+				lista[k] = Left[i]
42
+				i += 1 # Increments i
42 43
 			# If the compared number in i is greater than j it enters here
43
-            else:
44
+			else:
44 45
 				# The less variable is stored in the list again in order
45
-                lista[k] = Right[j]
46
-                j += 1 # Increments j
47
-            k += 1 # Increments k
46
+				lista[k] = Right[j]
47
+				j += 1 # Increments j
48
+			k += 1 # Increments k
48 49
 
49 50
 		# If there are elements remaining in Left the they are put here
50
-        while i < len(Left):
51
+		while i < len(Left):
51 52
 			# The variable that was remaining is put here
52
-            lista[k] = Left[i]
53
-            i += 1 # Increments i
54
-            k += 1 # Increments k
53
+			lista[k] = Left[i]
54
+			i += 1 # Increments i
55
+			k += 1 # Increments k
55 56
 
56 57
 		# If there are elements remaining in Right the they are put here
57
-        while j < len(Right):
58
+		while j < len(Right):
58 59
 			# The variable that was remaining is put here
59
-            lista[k] = Right[j]
60
-            j += 1 # Increments j
61
-            k += 1 # Increments k
60
+			lista[k] = Right[j]
61
+			j += 1 # Increments j
62
+			k += 1 # Increments k
62 63
 
63 64
 	return lista
64 65
 	# Code was base and taken from GeeksforGeeks
@@ -68,13 +69,15 @@ def heapSort(lista):
68 69
 	return lista
69 70
 
70 71
 def quickSort(lista):
71
-	 # Se aplica quicksort a la lista desde el primer elemento hasta el último
72
-	return qsortUtils.qSort(lista, 0, len(lista) - 1)
72
+	# Se aplica quicksort a la lista desde el primer elemento hasta el último
73
+	qsortUtils.qSort(lista, 0, len(lista) - 1)
74
+	
75
+	return lista
73 76
 
74 77
 def shellSort(lista):
75 78
 	#definan el algoritmo de ordenamiento shellsort
76 79
 	Size = len(lista) # Contains the complete size of the list
77
-	Diff = Size/2 # Contains the number of half of the list
80
+	Diff = Size//2 # Contains the number of half of the list
78 81
 
79 82
 	# Does a insertion sort by ordering in base of the Diff.
80 83
 	while Diff > 0:
@@ -92,47 +95,51 @@ def shellSort(lista):
92 95
 			# Puts the Tmp variable in is correct location
93 96
 			lista[j] = Tmp
94 97
 		# Reduces again the list
95
-		Diff /= 2
98
+		Diff //= 2
96 99
 
97 100
 	return lista
98 101
 	# Code was taken from GeeksforGeeks
99 102
 
100
-maxValor=1000 	#define el valor maximo de los elementos de la lista
101
-largoLista=1000 #define el largo de las listas a ordenar
102
-veces=100 		#define las veces que se va a hacer el ordenamiento
103
-
104
-acumulaMerge=0 	#variable para acumular el tiempo de ejecucion del mergesort
105
-acumulaHeap=0 	#variable para acumular el tiempo de ejecucion del heapsort
106
-acumulaQuick=0 	#variable para acumular el tiempo de ejecucion del quicksort
107
-
108
-
109
-acumulaShell=0 	#variable para acumular el tiempo de ejecucion del shellsort
110
-
111
-for i in range(veces):
112
-	mergelista = [randint(0,maxValor) for r in range(largoLista)] #creamos una lista con valores al azar
113
-	heaplista=list(mergelista)
114
-	quicklista=list(mergelista)
115
-	searchlista=list(mergelista)
116
-
117
-	t1 = time.perf_counter() 				#seteamos el tiempo al empezar
118
-	mergeSort(mergelista) 				#ejecutamos el algoritmo mergeSort
119
-	acumulaMerge+=time.perf_counter()-t1 	#acumulamos el tiempo de ejecucion
120
-	
121
-	t1 = time.perf_counter()			#seteamos el tiempo al empezar
122
-	heapSort(heaplista)					#ejecutamos el algoritmo heapSort
123
-	acumulaHeap+=time.perf_counter()-t1 	#acumulamos el tiempo de ejecucion
124
-	
125
-	t1 = time.perf_counter()				#seteamos el tiempo al empezar
126
-	quickSort(quicklista)				#ejecutamos el algoritmo quickSort
127
-	acumulaQuick+=time.perf_counter()-t1 	#acumulamos el tiempo de ejecucion
128
-	
129
-	t1 = time.perf_counter()				#seteamos el tiempo al empezar
130
-	shellSort(searchlista)				#ejecutamos el algoritmo shellSort
131
-	acumulaShell+=time.perf_counter()-t1 	#acumulamos el tiempo de ejecucion
132
-
133
-#imprimos los resultados
134
-print (f"Promedio de tiempo de ejecucion de {veces} listas de largo {largoLista}")
135
-print (f"MergeSort {str(acumulaMerge/veces)} segundos")
136
-print (f"HeapSort {str(acumulaHeap/veces)} segundos")
137
-print (f"QuickSort {str(acumulaQuick/veces)} segundos")
138
-print (f"ShellSort {str(acumulaShell/veces) }segundos")
103
+def main():
104
+	maxValor=1000 	#define el valor maximo de los elementos de la lista
105
+	largoLista=1000 #define el largo de las listas a ordenar
106
+	veces=100 		#define las veces que se va a hacer el ordenamiento
107
+
108
+	acumulaMerge=0 	#variable para acumular el tiempo de ejecucion del mergesort
109
+	acumulaHeap=0 	#variable para acumular el tiempo de ejecucion del heapsort
110
+	acumulaQuick=0 	#variable para acumular el tiempo de ejecucion del quicksort
111
+
112
+
113
+	acumulaShell=0 	#variable para acumular el tiempo de ejecucion del shellsort
114
+
115
+	for i in range(veces):
116
+		mergelista = [randint(0,maxValor) for r in range(largoLista)] #creamos una lista con valores al azar
117
+		heaplista=list(mergelista)
118
+		quicklista=list(mergelista)
119
+		searchlista=list(mergelista)
120
+
121
+		t1 = time.perf_counter() 				#seteamos el tiempo al empezar
122
+		mergeSort(mergelista) 				#ejecutamos el algoritmo mergeSort
123
+		acumulaMerge+=time.perf_counter()-t1 	#acumulamos el tiempo de ejecucion
124
+		
125
+		t1 = time.perf_counter()			#seteamos el tiempo al empezar
126
+		heapSort(heaplista)					#ejecutamos el algoritmo heapSort
127
+		acumulaHeap+=time.perf_counter()-t1 	#acumulamos el tiempo de ejecucion
128
+		
129
+		t1 = time.perf_counter()				#seteamos el tiempo al empezar
130
+		quickSort(quicklista)				#ejecutamos el algoritmo quickSort
131
+		acumulaQuick+=time.perf_counter()-t1 	#acumulamos el tiempo de ejecucion
132
+		
133
+		t1 = time.perf_counter()				#seteamos el tiempo al empezar
134
+		shellSort(searchlista)				#ejecutamos el algoritmo shellSort
135
+		acumulaShell+=time.perf_counter()-t1 	#acumulamos el tiempo de ejecucion
136
+
137
+	#imprimos los resultados
138
+	print (f"Promedio de tiempo de ejecucion de {veces} listas de largo {largoLista}")
139
+	print (f"MergeSort {str(acumulaMerge/veces)} segundos")
140
+	print (f"HeapSort {str(acumulaHeap/veces)} segundos")
141
+	print (f"QuickSort {str(acumulaQuick/veces)} segundos")
142
+	print (f"ShellSort {str(acumulaShell/veces) }segundos")
143
+
144
+if __name__ == "__main__":
145
+	main()

+ 64
- 9
test_sortAlgo.py View File

@@ -1,14 +1,69 @@
1
-from email import utils
1
+import sorting
2
+from random import randint
2 3
 
4
+DEBUG_OUTPUT = True
3 5
 
4
-from utils import qsortUtils
5
-from random import randint
6
+def test_mergeSort(pruebas):
7
+    FAIL = False
8
+
9
+    print("\nProbando MergeSort")
10
+
11
+    for nombre, lista in pruebas.items():
12
+        if sorting.mergeSort(lista) == sorted(lista):
13
+            print(f"{nombre}: " + "Pass")
14
+        else:
15
+            print(f"{nombre}: " + "Fail")
16
+            FAIL = True
17
+
18
+    if FAIL == True and DEBUG_OUTPUT == True:
19
+        print("\n Test FAIL OUTPUT for MergeSort")
20
+        for nombre, lista in pruebas.items():
21
+            print(f"{nombre}: Obtained -> {sorting.mergeSort(lista)} | Expected -> {sorted(lista)}")    
22
+
23
+def test_quickSort(pruebas):
24
+    FAIL = False
25
+
26
+    print("\nProbando QuickSort")
27
+
28
+    for nombre, lista in pruebas.items():
29
+        if sorting.quickSort(lista) == sorted(lista):
30
+            print(f"{nombre}: " + "Pass")
31
+        else:
32
+            print(f"{nombre}: " + "Fail")
33
+            FAIL = True
34
+
35
+    if FAIL == True and DEBUG_OUTPUT == True:
36
+        print("\n Test FAIL OUTPUT for QuickSort")
37
+        for nombre, lista in pruebas.items():
38
+            print(f"{nombre}: Obtained -> {sorting.quickSort(lista)} | Expected -> {sorted(lista)}")   
39
+
40
+def test_shellSort(pruebas):
41
+    FAIL = False
42
+
43
+    print("\nProbando ShellSort")
44
+
45
+    for nombre, lista in pruebas.items():
46
+        if sorting.shellSort(lista) == sorted(lista):
47
+            print(f"{nombre}: " + "Pass")
48
+        else:
49
+            print(f"{nombre}: " + "Fail")
50
+            FAIL = True
6 51
 
7
-enteros = [0,7,3,1,4,5,2]
8
-negativos = [8,-1,3,2,-4,9]
9
-aleatoria =[randint(-49,50) for r in range(10)]
52
+    if FAIL == True and DEBUG_OUTPUT == True:
53
+        print("\n Test FAIL OUTPUT for ShellSort")
54
+        for nombre, lista in pruebas.items():
55
+            print(f"{nombre}: Obtained -> {sorting.shellSort(lista)} | Expected -> {sorted(lista)}")   
10 56
 
11
-print(qsortUtils.qSort(enteros,0,len(enteros)-1) == enteros.sort())
12
-print(qsortUtils.qSort(negativos,0,len(negativos)-1) == negativos.sort())
13
-print(qsortUtils.qSort(aleatoria,0,len(aleatoria)-1) == aleatoria.sort())
57
+def main():
58
+    PRUEBAS = {"Enteros":[0,7,3,1,4,5,2],
59
+               "Negativos":[8,-1,3,2,-4,9],
60
+               "Aleatorios":[randint(-49,50) for r in range(10)],
61
+               "Vacia":[],
62
+               "Ordenada":[1,2,3,4,5,6,7]}
63
+    
64
+    test_mergeSort(PRUEBAS)
65
+    test_quickSort(PRUEBAS)
66
+    test_shellSort(PRUEBAS)
14 67
 
68
+if __name__ == "__main__":
69
+    main()

BIN
utils/__pycache__/qsortUtils.cpython-38.pyc View File


+ 10
- 9
utils/qsortUtils.py View File

@@ -1,24 +1,25 @@
1 1
 # Función partition: Selecciona el pivote y divide la lista en dos conjuntos: Elementos menores o iguales al pivote y elementos mayores al pivote
2
-def partition(lista, p, r): 
2
+def partition(A, p, r): 
3 3
 
4
-  x = lista[r] # Selección del último elemento en la lista como el pivote
4
+  x = A[r] # Selección del último elemento en la lista como el pivote
5 5
   i = p - 1 # El conjunto de elementos menores o iguales al pivote está inicialmente vacío
6 6
 
7 7
   for j in range (p, r):
8 8
 
9
-    if lista[j] <= x: # Comparación de elemento en la lista con el pivote
9
+    if A[j] <= x: # Comparación de elemento en la lista con el pivote
10 10
       i += 1 # Hacer espacio para el elemento A[j], se coloca un espacio luego del último elemento del conjunto de elementos menores o iguales al pivote.
11
-      lista[j], lista[i] = lista[i], lista[j] #Swap A[j] con A[i]
11
+      A[j], A[i] = A[i], A[j] #Swap A[j] con A[i]
12 12
 
13
-  lista[i+1], lista[r] = lista[r], lista[i+1] # Colocar el pivote como último elemento del conjunto de menores o iguales
13
+  A[i+1], A[r] = A[r], A[i+1] # Colocar el pivote como último elemento del conjunto de menores o iguales
14 14
 
15 15
   return i + 1 # Devuelve el índice del pivote actual
16 16
 
17 17
 # Función qSort: Aplica el algoritmo de Quicksort a una lista
18
-def qSort(lista, p, r):
18
+def qSort(A, p, r):
19 19
 
20 20
   if p < r: # Caso Base: Se llegó a un elemento individual. La lista es un solo elemento
21
-    q = partition(lista, p, r) # Divide/Combine: Particiona la lista y se obtiene el índice del pivote
22
-    qSort(lista, p, q - 1) # Conquer: Se aplica qSort al conjunto de elementos menores o iguales al pivote actual
23
-    qSort(lista, q + 1, r) # Conquer: Se aplica qSort al conjunto de elementos mayores al pivote actual
21
+    q = partition(A, p, r) # Divide/Combine: Particiona la lista y se obtiene el índice del pivote
22
+    qSort(A, p, q - 1) # Conquer: Se aplica qSort al conjunto de elementos menores o iguales al pivote actual
23
+    qSort(A, q + 1, r) # Conquer: Se aplica qSort al conjunto de elementos mayores al pivote actual
24
+
24 25