Ejercicio 15b

This commit is contained in:
perro tuerto 2023-05-24 08:55:53 -07:00
parent 98d82c145a
commit 4e9535e737
2 changed files with 116 additions and 0 deletions

71
exercises/ex15/queue.py Normal file
View File

@ -0,0 +1,71 @@
class QueueNode(object):
def __init__(self, value, prev, nxt):
self.value = value
self.next = nxt
self.prev = prev
def __repr__(self):
nval = self.next and self.next.value or None
pval = self.prev and self.prev.value or None
return f"[{repr(pval)}, {self.value}, {repr(nval)}]"
class Queue(object):
def __init__(self):
self.begin = None
self.end = None
def count(self):
"""
Returns number of items.
Regresa la cantidad de ítems.
"""
count = 0
node = self.begin
while node:
count += 1
node = node.next
return count
def unshift(self):
"""
Removes the first item and returns its value.
Remueve el primer ítem y regresa su valor.
"""
if self.begin is None:
value = None
else:
value = self.begin.value
if self.begin == self.end:
self.begin = self.end = None
else:
self.begin = self.begin.next
self.begin.prev = None
return value
def shift(self, obj):
"""
Appends a new item on the begin of the list.
Añade un nuevo ítem al inicio de la lista.
"""
node = QueueNode(obj, None, self.begin)
if self.begin is None:
self.begin = node
self.end = self.begin
else:
self.begin.prev = node
self.begin = node
def top(self):
"""
Returns value of first item.
Regresa el valor del primer ítem.
"""
return self.begin.value
def bottom(self):
"""
Returns value of last item.
Regresa el valor del último ítem.
"""
return self.end.value

View File

@ -0,0 +1,45 @@
from queue import Queue
def test_unshift():
colors = Queue()
colors.shift("Viridian")
colors.shift("Sap Green")
colors.shift("Van Dyke")
assert colors.unshift() == "Van Dyke"
assert colors.unshift() == "Sap Green"
assert colors.unshift() == "Viridian"
assert colors.unshift() is None
assert colors.count() == 0
def test_shift():
colors = Queue()
colors.shift("Cadmium Orange")
assert colors.count() == 1
colors.shift("Carbazole Violet")
assert colors.count() == 2
assert colors.unshift() == "Carbazole Violet"
assert colors.count() == 1
assert colors.unshift() == "Cadmium Orange"
assert colors.count() == 0
def test_top():
colors = Queue()
colors.shift("Cadmium Red Light")
assert colors.top() == "Cadmium Red Light"
colors.shift("Hansa Yellow")
assert colors.top() == "Hansa Yellow"
colors.shift("Pthalo Green")
assert colors.top() == "Pthalo Green"
def test_bottom():
colors = Queue()
colors.shift("Cadmium Red Light")
assert colors.bottom() == "Cadmium Red Light"
colors.shift("Hansa Yellow")
assert colors.bottom() == "Cadmium Red Light"
colors.shift("Pthalo Green")
assert colors.bottom() == "Cadmium Red Light"