Skip to content

Commit

Permalink
arreglo iteradores
Browse files Browse the repository at this point in the history
  • Loading branch information
dariocorreal committed Apr 16, 2021
1 parent 362790e commit 998e026
Show file tree
Hide file tree
Showing 26 changed files with 522 additions and 297 deletions.
14 changes: 4 additions & 10 deletions App/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
from DISClib.ADT.graph import gr
from DISClib.ADT import map as m
from DISClib.ADT import list as lt
from DISClib.DataStructures import listiterator as it
from DISClib.Algorithms.Graphs import scc
from DISClib.Algorithms.Graphs import dijsktra as djk
from DISClib.Utils import error as error
Expand Down Expand Up @@ -139,14 +138,11 @@ def addRouteConnections(analyzer):
que se puede realizar en una estación.
"""
lststops = m.keySet(analyzer['stops'])
stopsiterator = it.newIterator(lststops)
while it.hasNext(stopsiterator):
key = it.next(stopsiterator)
for key in lt.iterator(lststops):
lstroutes = m.get(analyzer['stops'], key)['value']
prevrout = None
routeiterator = it.newIterator(lstroutes)
while it.hasNext(routeiterator):
route = key + '-' + it.next(routeiterator)
for route in lt.iterator(lstroutes):
route = key + '-' + route
if prevrout is not None:
addConnection(analyzer, prevrout, route, 0)
addConnection(analyzer, route, prevrout, 0)
Expand Down Expand Up @@ -224,11 +220,9 @@ def servedRoutes(analyzer):
retorna una de ellas
"""
lstvert = m.keySet(analyzer['stops'])
itlstvert = it.newIterator(lstvert)
maxvert = None
maxdeg = 0
while(it.hasNext(itlstvert)):
vert = it.next(itlstvert)
for vert in lt.iterator(lstvert):
lstroutes = m.get(analyzer['stops'], vert)['value']
degree = lt.size(lstroutes)
if(degree > maxdeg):
Expand Down
41 changes: 38 additions & 3 deletions DISClib/ADT/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,39 @@
"""


def newList(datastructure='SINGLE_LINKED', cmpfunction=None):
def newList(datastructure='SINGLE_LINKED',
cmpfunction=None,
key=None,
filename=None,
delimiter=","):
"""Crea una lista vacia
Args:
cmpfunction: Función de comparación para los elementos de la lista
datastructure: Tipo de estructura de datos a utilizar para implementar
la lista. Los tipos posibles pueden ser: ARRAY_LIST y SINGLE_LINKED.
cmpfunction: Función de comparación para los elementos de la lista.
Si no se provee función de comparación se utiliza la función
por defecto pero se debe proveer un valor para key.
Si se provee una función de comparación el valor de Key debe ser None.
Key: Identificador utilizado para comparar dos elementos de la lista
con la función de comaparación por defecto.
filename: Si se provee este valor, se crea una lista a partir
de los elementos encontrados en el archivo.
Se espera que sea un archivo CSV UTF8.
delimiter: Si se pasa un archivo en el parámetro filename, se utiliza
este valor para separar los campos. El valor por defecto es una coma.
Returns:
Una nueva lista
Raises:
Exception
"""
try:
lst = lt.newList(datastructure, cmpfunction)
lst = lt.newList(datastructure, cmpfunction, key, filename, delimiter)
return lst
except Exception as exp:
error.reraise(exp, 'TADList->newList: ')
Expand Down Expand Up @@ -341,3 +362,17 @@ def subList(lst, pos, numelem):
return lt.subList(lst, pos, numelem)
except Exception as exp:
error.reraise(exp, 'List->subList: ')


def iterator(lst):
""" Retorna un iterador para la lista.
Args:
lst: La lista a iterar
Raises:
Exception
"""
try:
return lt.iterator(lst)
except Exception as exp:
error.reraise(exp, 'List->Iterator: ')
5 changes: 4 additions & 1 deletion DISClib/ADT/stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ def pop(stack):
Exception
"""
try:
return lt.removeFirst(stack)
if stack is not None and not lt.isEmpty(stack):
return lt.removeFirst(stack)
else:
raise Exception
except Exception as exp:
error.reraise(exp, 'TADStack->pop: ')

Expand Down
6 changes: 2 additions & 4 deletions DISClib/Algorithms/Graphs/bfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@

import config
from DISClib.ADT import graph as g
from DISClib.DataStructures import listiterator as it
from DISClib.ADT import queue
from DISClib.ADT import map as map
from DISClib.ADT import list as lt
from DISClib.ADT import stack
from DISClib.Utils import error as error
assert config
Expand Down Expand Up @@ -84,9 +84,7 @@ def bfsVertex(search, graph, source):
vertex = queue.dequeue(adjsqueue)
visited_v = map.get(search['visited'], vertex)['value']
adjslst = g.adjacents(graph, vertex)
adjslstiter = it.newIterator(adjslst)
while (it.hasNext(adjslstiter)):
w = it.next(adjslstiter)
for w in lt.iterator(adjslst):
visited_w = map.get(search['visited'], w)
if visited_w is None:
dist_to_w = visited_v['distTo'] + 1
Expand Down
10 changes: 3 additions & 7 deletions DISClib/Algorithms/Graphs/dfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"""

import config
from DISClib.DataStructures import listiterator as it
from DISClib.ADT import list as lt
from DISClib.ADT import graph as g
from DISClib.ADT import queue
from DISClib.ADT import stack
Expand All @@ -50,9 +50,7 @@ def DepthFirstOrder(graph):
comparefunction=graph['comparefunction']
)
lstvert = g.vertices(graph)
vertiterator = it.newIterator(lstvert)
while it.hasNext(vertiterator):
vertex = it.next(vertiterator)
for vertex in lt.iterator(lstvert):
if not (map.contains(search['marked'], vertex)):
dfsVertex(graph, search, vertex)
return search
Expand All @@ -76,9 +74,7 @@ def dfsVertex(graph, search, vertex):
queue.enqueue(search['pre'], vertex)
map.put(search['marked'], vertex, True)
lstadjacents = g.adjacents(graph, vertex)
adjiterator = it.newIterator(lstadjacents)
while it.hasNext(adjiterator):
adjvert = it.next(adjiterator)
for adjvert in lt.iterator(lstadjacents):
if not map.contains(search['marked'], adjvert):
dfsVertex(graph,
search,
Expand Down
6 changes: 2 additions & 4 deletions DISClib/Algorithms/Graphs/dfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

import config
from DISClib.DataStructures import adjlist as g
from DISClib.DataStructures import listiterator as it
from DISClib.ADT import list as lt
from DISClib.ADT import map as map
from DISClib.ADT import stack as stk
from DISClib.Utils import error as error
Expand Down Expand Up @@ -77,9 +77,7 @@ def dfsVertex(search, graph, vertex):
"""
try:
adjlst = g.adjacents(graph, vertex)
adjslstiter = it.newIterator(adjlst)
while (it.hasNext(adjslstiter)):
w = it.next(adjslstiter)
for w in lt.iterator(adjlst):
visited = map.get(search['visited'], w)
if visited is None:
map.put(search['visited'],
Expand Down
10 changes: 3 additions & 7 deletions DISClib/Algorithms/Graphs/dijsktra.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

import config
from DISClib.DataStructures import edge as e
from DISClib.DataStructures import listiterator as it
from DISClib.ADT import list as lt
from DISClib.ADT import indexminpq as iminpq
from DISClib.ADT import map as map
from DISClib.ADT import graph as g
Expand Down Expand Up @@ -55,9 +55,7 @@ def Dijkstra(graph, source):
v = iminpq.delMin(search['iminpq'])
edges = g.adjacentEdges(graph, v)
if edges is not None:
edgesiter = it.newIterator(edges)
while (it.hasNext(edgesiter)):
edge = it.next(edgesiter)
for edge in lt.iterator(edges):
relax(search, edge)
return search
except Exception as exp:
Expand Down Expand Up @@ -197,9 +195,7 @@ def initSearch(graph, source):
comparefunction=graph['comparefunction']
)
vertices = g.vertices(graph)
itvertices = it.newIterator(vertices)
while (it.hasNext(itvertices)):
vert = it.next(itvertices)
for vert in lt.iterator(vertices):
map.put(search['visited'],
vert,
{'marked': False, 'edgeTo': None, 'distTo': math.inf}
Expand Down
18 changes: 5 additions & 13 deletions DISClib/Algorithms/Graphs/scc.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"""

import config
from DISClib.DataStructures import listiterator as it
from DISClib.ADT import list as lt
from DISClib.ADT import graph as g
from DISClib.ADT import stack
from DISClib.Algorithms.Graphs import dfo
Expand Down Expand Up @@ -95,9 +95,7 @@ def sccCount(graph, scc, vert):
map.put(scc['marked'], vert, True)
map.put(scc['idscc'], vert, scc['components'])
lstadjacents = g.adjacents(graph, vert)
adjiterator = it.newIterator(lstadjacents)
while it.hasNext(adjiterator):
adjvert = it.next(adjiterator)
for adjvert in lt.iterator(lstadjacents):
if not map.contains(scc['marked'], adjvert):
sccCount(graph, scc, adjvert)
return scc
Expand Down Expand Up @@ -144,18 +142,12 @@ def reverseGraph(graph):
)

lstvert = g.vertices(graph)
itervert = it.newIterator(lstvert)
while it.hasNext(itervert):
vert = it.next(itervert)
for vert in lt.iterator(lstvert):
g.insertVertex(greverse, vert)

itervert = it.newIterator(lstvert)
while it.hasNext(itervert):
vert = it.next(itervert)
for vert in lt.iterator(lstvert):
lstadj = g.adjacents(graph, vert)
iteradj = it.newIterator(lstadj)
while it.hasNext(iteradj):
adj = it.next(iteradj)
for adj in lt.iterator(lstadj):
g.addEdge(greverse, adj, vert)
return greverse
except Exception as exp:
Expand Down
7 changes: 4 additions & 3 deletions DISClib/Algorithms/Sorting/insertionsort.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,14 @@
"""


def insertionSort(lst, lessfunction):
def sort(lst, cmpfunction):
size = lt.size(lst)
pos1 = 1
while pos1 <= size:
pos2 = pos1
while (pos2 > 1) and (lessfunction(
(lt.getElement(lst, pos2), lt.getElement(lst, pos2-1)))):
while (pos2 > 1) and (cmpfunction(
lt.getElement(lst, pos2), lt.getElement(lst, pos2-1))):
lt.exchange(lst, pos2, pos2-1)
pos2 -= 1
pos1 += 1
return lst
9 changes: 5 additions & 4 deletions DISClib/Algorithms/Sorting/mergesort.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"""


def mergesort(lst, lessfunction):
def sort(lst, cmpfunction):
size = lt.size(lst)
if size > 1:
mid = (size // 2)
Expand All @@ -46,8 +46,8 @@ def mergesort(lst, lessfunction):
rightlist = lt.subList(lst, mid+1, size - mid)

"""se hace el llamado recursivo con la lista izquierda y derecha"""
mergesort(leftlist, lessfunction)
mergesort(rightlist, lessfunction)
sort(leftlist, cmpfunction)
sort(rightlist, cmpfunction)

"""i recorre la lista izquierda, j la derecha y k la lista original"""
i = j = k = 1
Expand All @@ -59,7 +59,7 @@ def mergesort(lst, lessfunction):
elemi = lt.getElement(leftlist, i)
elemj = lt.getElement(rightlist, j)
"""compara y ordena los elementos"""
if lessfunction(elemj, elemi): # caso estricto elemj < elemi
if cmpfunction(elemj, elemi): # caso estricto elemj < elemi
lt.changeInfo(lst, k, elemj)
j += 1
else: # caso elemi <= elemj
Expand All @@ -77,3 +77,4 @@ def mergesort(lst, lessfunction):
lt.changeInfo(lst, k, lt.getElement(rightlist, j))
j += 1
k += 1
return lst
19 changes: 10 additions & 9 deletions DISClib/Algorithms/Sorting/quicksort.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,35 +36,36 @@
"""


def partition(lst, lo, hi, lessequalfunction):
def partition(lst, lo, hi, cmpfunction):
"""
Función que va dejando el pivot en su lugar, mientras mueve
elementos menores a la izquierda del pivot y elementos mayores a
la derecha del pivot
"""
follower = leader = lo
while leader < hi:
if (lessequalfunction(
(lt.getElement(lst, leader), lt.getElement(lst, hi)))):
if cmpfunction(
lt.getElement(lst, leader), lt.getElement(lst, hi)):
lt.exchange(lst, follower, leader)
follower += 1
leader += 1
lt.exchange(lst, follower, hi)
return follower


def sort(lst, lo, hi, lessequalfunction):
def quicksort(lst, lo, hi, cmpfunction):
"""
Se localiza el pivot, utilizando la funcion de particion.
Luego se hace la recursión con los elementos a la izquierda del pivot
y los elementos a la derecha del pivot
"""
if (lo >= hi):
return
pivot = partition(lst, lo, hi, lessequalfunction)
sort(lst, lo, pivot-1, lessequalfunction)
sort(lst, pivot+1, hi, lessequalfunction)
pivot = partition(lst, lo, hi, cmpfunction)
quicksort(lst, lo, pivot-1, cmpfunction)
quicksort(lst, pivot+1, hi, cmpfunction)


def quickSort(lst, lessequalfunction):
sort(lst, 1, lt.size(lst), lessequalfunction)
def sort(lst, cmpfunction):
quicksort(lst, 1, lt.size(lst), cmpfunction)
return lst
5 changes: 3 additions & 2 deletions DISClib/Algorithms/Sorting/selectionsort.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,17 @@
"""


def selectionSort(lst, lessfunction):
def sort(lst, cmpfunction):
size = lt.size(lst)
pos1 = 1
while pos1 < size:
minimum = pos1 # minimun tiene el menor elemento
pos2 = pos1 + 1
while (pos2 <= size):
if (lessfunction(lt.getElement(lst, pos2),
if (cmpfunction(lt.getElement(lst, pos2),
(lt.getElement(lst, minimum)))):
minimum = pos2 # minimum = posición elemento más pequeño
pos2 += 1
lt.exchange(lst, pos1, minimum) # elemento más pequeño -> elem pos1
pos1 += 1
return lst
9 changes: 5 additions & 4 deletions DISClib/Algorithms/Sorting/shellsort.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,18 @@
"""


def shellSort(lst, lessfunction):
def sort(lst, cmpfunction):
n = lt.size(lst)
h = 1
while h < n/3: # primer gap. La lista se h-ordena con este tamaño
h = 3*h + 1
while (h >= 1):
for i in range(h, n):
j = i
ant = lt.getElement(lst, j+1)
post = lt.getElement(lst, j-h+1)
while (j >= h) and lessfunction(ant, post):
while (j >= h) and cmpfunction(
lt.getElement(lst, j+1),
lt.getElement(lst, j-h+1)):
lt.exchange(lst, j+1, j-h+1)
j -= h
h //= 3 # h se decrementa en un tercio
return lst
Loading

0 comments on commit 998e026

Please sign in to comment.