From 98d82c145abc5c1e794526a36eb0196c93cef302 Mon Sep 17 00:00:00 2001 From: perro Date: Mon, 22 May 2023 10:49:10 -0700 Subject: [PATCH] Ejercicio 15a --- exercises/ex15/stack.py | 70 ++++++++++++++++++++++++++++++++++++ exercises/ex15/test_stack.py | 32 +++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 exercises/ex15/stack.py create mode 100644 exercises/ex15/test_stack.py diff --git a/exercises/ex15/stack.py b/exercises/ex15/stack.py new file mode 100644 index 0000000..80e3df5 --- /dev/null +++ b/exercises/ex15/stack.py @@ -0,0 +1,70 @@ +class StackNode(object): + def __init__(self, value, nxt): + self.value = value + self.next = nxt + + def __repr__(self): + nval = self.next and self.next.value or None + return f"[{self.value}:{repr(nval)}]" + + +class Stack(object): + def __init__(self): + self.topmost = None + + def push(self, obj): + """ + Pushes a new value to the top of the stack. + Añade un nuevo valor en el tope del stack. + """ + if not self.topmost: + self.topmost = StackNode(obj, None) + else: + self.topmost = StackNode(obj, self.topmost) + + def pop(self): + """ + Pops the value that is currently on the top of the stack. + Remueve el valor que está en el tope del stack. + """ + if self.topmost: + node = self.topmost + if self.topmost.next: + self.topmost = self.topmost.next + else: + self.topmost = None + return node.value + + def top(self): + """ + Returns the reference to the first item, does not remove. + Regresa la referencia al primer ítem sin removerlo. + """ + if self.topmost: + return self.topmost.value + + def count(self): + """ + Returns number of items. + Regresa la cantidad de ítems. + """ + count = 0 + if self.topmost: + node = self.topmost + while node: + count += 1 + node = node.next + return count + + def dump(self, mark="----"): + """ + Debugging function that dumps the contents of the stack. + Función de depuración que arroja los contenidos del stack. + """ + if self.topmost: + node = self.topmost + print(node.value) + while node.next: + node = node.next + print(mark) + print(node.value) diff --git a/exercises/ex15/test_stack.py b/exercises/ex15/test_stack.py new file mode 100644 index 0000000..2defd41 --- /dev/null +++ b/exercises/ex15/test_stack.py @@ -0,0 +1,32 @@ +from stack import Stack + + +def test_push(): + colors = Stack() + colors.push("Pthalo Blue") + assert colors.count() == 1 + colors.push("Ultramarine Blue") + assert colors.count() == 2 + + +def test_pop(): + colors = Stack() + colors.push("Magenta") + colors.push("Alizarin") + assert colors.pop() == "Alizarin" + assert colors.count() == 1 + assert colors.pop() == "Magenta" + assert colors.count() == 0 + assert colors.pop() is None + + +def test_top(): + colors = Stack() + colors.push("Cadmium Red Light") + assert colors.top() == "Cadmium Red Light" + colors.push("Hansa Yellow") + assert colors.top() == "Hansa Yellow" + colors.pop() + assert colors.top() == "Cadmium Red Light" + colors.pop() + assert colors.top() is None