|
| 1 | +#7 { Retos para Programadores } PILAS Y COLAS |
| 2 | +""" |
| 3 | + * EJERCICIO: |
| 4 | + * Implementa los mecanismos de introducción y recuperación de elementos propios de las |
| 5 | + * pilas (stacks - LIFO) y las colas (queue - FIFO) utilizando una estructura de array |
| 6 | + * o lista (dependiendo de las posibilidades de tu lenguaje). |
| 7 | + * |
| 8 | + * DIFICULTAD EXTRA (opcional): |
| 9 | + * - Utilizando la implementación de pila y cadenas de texto, simula el mecanismo adelante/atrás |
| 10 | + * de un navegador web. Crea un programa en el que puedas navegar a una página o indicarle |
| 11 | + * que te quieres desplazar adelante o atrás, mostrando en cada caso el nombre de la web. |
| 12 | + * Las palabras "adelante", "atrás" desencadenan esta acción, el resto se interpreta como |
| 13 | + * el nombre de una nueva web. |
| 14 | + * - Utilizando la implementación de cola y cadenas de texto, simula el mecanismo de una |
| 15 | + * impresora compartida que recibe documentos y los imprime cuando así se le indica. |
| 16 | + * La palabra "imprimir" imprime un elemento de la cola, el resto de palabras se |
| 17 | + * interpretan como nombres de documentos. |
| 18 | +""" |
| 19 | + |
| 20 | +# The list structure in Python can be useful to simulate stacks and queues. |
| 21 | + |
| 22 | +# A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. |
| 23 | +# This means that the last element added to the stack is the first one to be removed. |
| 24 | +# You can think of it like a stack of plates: you add plates to the top and also remove them from the top. |
| 25 | +# Key Operations: |
| 26 | +# - Push: Add an element to the top of the stack. |
| 27 | +# - Pop: Remove the element from the top of the stack. |
| 28 | +# - Peek/Top: Retrieve the top element without removing it. |
| 29 | +# - IsEmpty: Check if the stack is empty. |
| 30 | + |
| 31 | +log = print |
| 32 | + |
| 33 | +# Stack implementation using a list |
| 34 | +stack = [1, 2, 3, 4] |
| 35 | + |
| 36 | +# View the contents of a stack |
| 37 | +log('View stack:', stack) # View stack: [1, 2, 3, 4] |
| 38 | + |
| 39 | +# Add an element to the stack |
| 40 | +stack.append(5) |
| 41 | +log('Add an element:', stack) # Add an element: [1, 2, 3, 4, 5] |
| 42 | + |
| 43 | +# Get the size of the stack |
| 44 | +log('Size:', len(stack)) # Size: 5 |
| 45 | + |
| 46 | +# Get the last value of the stack |
| 47 | +log('Last value of the stack:', stack[-1]) # Last value of the stack: 5 |
| 48 | + |
| 49 | +# Remove the last value from the stack and print its value |
| 50 | +log('Delete and return the last value:', stack.pop()) # Delete and return the last value: 5 |
| 51 | + |
| 52 | +# Empty the stack |
| 53 | +stack = [] |
| 54 | +log('Empty the stack:', stack) # Empty the stack: [] |
| 55 | + |
| 56 | +# We can also enclose the stack operations in a class for better organization and reusability |
| 57 | +class Stack: |
| 58 | + def __init__(self, initial_items=None): |
| 59 | + # Initialize the stack with an optional list of items |
| 60 | + self.items = initial_items if isinstance(initial_items, list) else [] |
| 61 | + |
| 62 | + def push(self, element): |
| 63 | + # Add an element to the top of the stack |
| 64 | + self.items.append(element) |
| 65 | + |
| 66 | + def pop(self): |
| 67 | + # Remove the element from the top of the stack |
| 68 | + if self.is_empty(): |
| 69 | + log("Stack is empty. Cannot pop an element.") |
| 70 | + return None |
| 71 | + return self.items.pop() |
| 72 | + |
| 73 | + def peek(self): |
| 74 | + # Retrieve the top element without removing it |
| 75 | + if self.is_empty(): |
| 76 | + log("Stack is empty. Cannot peek.") |
| 77 | + return None |
| 78 | + return self.items[-1] |
| 79 | + |
| 80 | + def empty(self): |
| 81 | + # Empty the stack |
| 82 | + self.items = [] |
| 83 | + |
| 84 | + def is_empty(self): |
| 85 | + # Check if the stack is empty |
| 86 | + return len(self.items) == 0 |
| 87 | + |
| 88 | + def size(self): |
| 89 | + # Get the size of the stack |
| 90 | + return len(self.items) |
| 91 | + |
| 92 | +# Create a new stack instance |
| 93 | +stack2 = Stack([55, 76, 98, 100]) |
| 94 | +log('Initial stack2:', stack2.items) # [55, 76, 98, 100] |
| 95 | + |
| 96 | +stack2.push(32) |
| 97 | +log('After pushing 32:', stack2.items) # [55, 76, 98, 100, 32] |
| 98 | + |
| 99 | +log('Peek:', stack2.peek()) # 32 |
| 100 | + |
| 101 | +log('Pop:', stack2.pop()) # 32 |
| 102 | +log('After popping:', stack2.items) # [55, 76, 98, 100] |
| 103 | + |
| 104 | +log('Pop all elements:') |
| 105 | +while not stack2.is_empty(): |
| 106 | + log('Popped:', stack2.pop()) |
| 107 | +# or we can just empty the stack |
| 108 | +# stack2.empty() |
| 109 | + |
| 110 | +log('Final stack2:', stack2.items) # [] |
| 111 | +log('Pop from empty stack2:', stack2.pop()) # Stack is empty. |
| 112 | +# Cannot pop an element. & None |
| 113 | + |
| 114 | +# Queue implementation |
| 115 | +# A queue is a linear data structure that follows the First In, First Out (FIFO) principle. |
| 116 | +# This means that the first element added to the queue is the first one to be removed. |
| 117 | +# You can think of it like a line of people waiting for service: the first person in line is the first to be served. |
| 118 | +# Key Operations: |
| 119 | +# - Enqueue: Add an element to the end of the queue. |
| 120 | +# - Dequeue: Remove the element from the front of the queue. |
| 121 | +# - Front/Peek: Retrieve the front element without removing it. |
| 122 | +# - IsEmpty: Check if the queue is empty. |
| 123 | + |
| 124 | +# Queue implementation using a list |
| 125 | +queue = [8, 5, 4, 2, 1] |
| 126 | + |
| 127 | +# View the contents of a queue |
| 128 | +log('View queue:', queue) # View queue: [8, 5, 4, 2, 1] |
| 129 | + |
| 130 | +# Add elements to the queue |
| 131 | +# Add elements to the queue |
| 132 | +queue.append(7) |
| 133 | +log('Add an element:', queue) # Add an element: [8, 5, 4, 2, 1, 7] |
| 134 | + |
| 135 | +# Get the size of the queue |
| 136 | +log('Size:', len(queue)) # Size: 6 |
| 137 | + |
| 138 | +# Get the first value of the queue |
| 139 | +log('First value:', queue[0]) # First value: 8 |
| 140 | + |
| 141 | +# Remove the first value from the queue and log its value |
| 142 | +log('Delete and return the first value:', queue.pop(0)) # Delete and return the first value: 8 |
| 143 | + |
| 144 | +# Empty the queue |
| 145 | +queue = [] |
| 146 | +log('Empty the queue:', queue) # Empty the queue: [] |
| 147 | + |
| 148 | +# We can also enclose the queue operations in a class for better organization and reusability |
| 149 | +class Queue: |
| 150 | + def __init__(self, initial_items=None): |
| 151 | + # Initialize the queue with an optional list of items |
| 152 | + self.items = initial_items if isinstance(initial_items, list) else [] |
| 153 | + |
| 154 | + def enqueue(self, element): |
| 155 | + # Add an element to the end of the queue |
| 156 | + self.items.append(element) |
| 157 | + |
| 158 | + def dequeue(self): |
| 159 | + # Remove the element from the front of the queue |
| 160 | + if self.is_empty(): |
| 161 | + log("Queue is empty. Cannot dequeue an element.") |
| 162 | + return None |
| 163 | + return self.items.pop(0) |
| 164 | + |
| 165 | + def front(self): |
| 166 | + # Retrieve the front element without removing it |
| 167 | + if self.is_empty(): |
| 168 | + log("Queue is empty. Cannot peek.") |
| 169 | + return None |
| 170 | + return self.items[0] |
| 171 | + |
| 172 | + def empty(self): |
| 173 | + # Empty the queue |
| 174 | + self.items = [] |
| 175 | + |
| 176 | + def is_empty(self): |
| 177 | + # Check if the queue is empty |
| 178 | + return len(self.items) == 0 |
| 179 | + |
| 180 | + def size(self): |
| 181 | + # Get the size of the queue |
| 182 | + return len(self.items) |
| 183 | + |
| 184 | +# Create a new queue instance |
| 185 | +queue2 = Queue([8, 5, 4, 2, 1]) |
| 186 | +log('Initial queue2:', queue2.items) # [8, 5, 4, 2, 1] |
| 187 | + |
| 188 | +queue2.enqueue(7) |
| 189 | +log('After enqueueing 7:', queue2.items) # [8, 5, 4, 2, 1, 7] |
| 190 | + |
| 191 | +log('Front:', queue2.front()) # 8 |
| 192 | + |
| 193 | +log('Dequeue:', queue2.dequeue()) # 8 |
| 194 | +log('After dequeueing:', queue2.items) # [5, 4, 2, 1, 7] |
| 195 | + |
| 196 | +log('Dequeue all elements:') |
| 197 | +while not queue2.is_empty(): |
| 198 | + log('Dequeued:', queue2.dequeue()) |
| 199 | +# or we can just empty the queue |
| 200 | +# queue2.empty() |
| 201 | + |
| 202 | +log('Final queue2:', queue2.items) # [] |
| 203 | +log('Dequeue from empty queue2:', queue2.dequeue()) # Dequeue from empty queue2:. |
| 204 | +# Cannot dequeue an element. & None |
| 205 | + |
| 206 | + # Additional exercises: |
| 207 | + |
| 208 | + # Simulate the behavior of the back and forward buttons in a browser. |
| 209 | + |
| 210 | +# List of documents to print |
| 211 | +documents_queue = [ |
| 212 | + {'name': 'Tratado de Tantra.txt', 'content': 'Here comes the content of Tratado de Tantra.'}, |
| 213 | + {'name': 'Nada Sagrado.doc', 'content': 'Here comes the content of Nada Sagrado.'}, |
| 214 | + {'name': 'El Blanco Invisible.pdf', 'content': 'Here comes the content of El Blanco Invisible.'} |
| 215 | +] |
| 216 | + |
| 217 | +def print_queue(arr): |
| 218 | + if len(arr) == 0: |
| 219 | + log('There are no elements to print in the queue!') |
| 220 | + return |
| 221 | + while len(arr) > 0: |
| 222 | + document = arr.pop(0) # Get the first document |
| 223 | + log('Printing document:', document['name']) |
| 224 | + log('Content:', document['content']) |
| 225 | + log('There are no more elements to print in the queue!') |
| 226 | + |
| 227 | +print_queue(documents_queue) |
| 228 | +# Output: |
| 229 | +# Printing document: Tratado de Tantra.txt |
| 230 | +# Content: Here comes the content of Tratado de Tantra. |
| 231 | +# Printing document: Nada Sagrado.doc |
| 232 | +# Content: Here comes the content of Nada Sagrado. |
| 233 | +# Printing document: El Blanco Invisible.pdf |
| 234 | +# Content: Here comes the content of El Blanco Invisible. |
| 235 | +# There are no more elements to print in the queue! |
| 236 | + |
| 237 | +# Simulate the behavior of the back and forward buttons in a browser. |
| 238 | + |
| 239 | +# List of documents to print |
| 240 | +documents_queue = [ |
| 241 | + {'name': 'Tratado de Tantra.txt', 'content': 'Here comes the content of Tratado de Tantra.'}, |
| 242 | + {'name': 'Nada Sagrado.doc', 'content': 'Here comes the content of Nada Sagrado.'}, |
| 243 | + {'name': 'El Blanco Invisible.pdf', 'content': 'Here comes the content of El Blanco Invisible.'} |
| 244 | +] |
| 245 | + |
| 246 | +def print_queue(arr): |
| 247 | + if len(arr) == 0: |
| 248 | + log('There are no elements to print in the queue!') |
| 249 | + return |
| 250 | + while len(arr) > 0: |
| 251 | + document = arr.pop(0) # Get the first document |
| 252 | + log('Printing document:', document['name']) |
| 253 | + log('Content:', document['content']) |
| 254 | + log('There are no more elements to print in the queue!') |
| 255 | + |
| 256 | +print_queue(documents_queue) |
| 257 | +# Output: |
| 258 | +# Printing document: Tratado de Tantra.txt |
| 259 | +# Content: Here comes the content of Tratado de Tantra. |
| 260 | +# Printing document: Nada Sagrado.doc |
| 261 | +# Content: Here comes the content of Nada Sagrado. |
| 262 | +# Printing document: El Blanco Invisible.pdf |
| 263 | +# Content: Here comes the content of El Blanco Invisible. |
| 264 | +# There are no more elements to print in the queue! |
| 265 | + |
| 266 | +# Simulating browser navigation |
| 267 | +url_stack = [] |
| 268 | +current_index = -1 # To keep track of the current position. |
| 269 | + |
| 270 | +def browse_web(url): |
| 271 | + global current_index, url_stack # Declare these variables as global |
| 272 | + |
| 273 | + def back(): |
| 274 | + global current_index # Declare current_index as global |
| 275 | + if current_index > 0: |
| 276 | + current_index -= 1 |
| 277 | + previous_url = url_stack[current_index] |
| 278 | + log('Location:', previous_url) |
| 279 | + else: |
| 280 | + log("There are no more pages back..") |
| 281 | + |
| 282 | + def forward(): |
| 283 | + global current_index # Declare current_index as global |
| 284 | + if current_index < len(url_stack) - 1: |
| 285 | + current_index += 1 |
| 286 | + next_url = url_stack[current_index] |
| 287 | + log('Location:', next_url) |
| 288 | + else: |
| 289 | + log("There are no more pages forward.") |
| 290 | + |
| 291 | + if url != 'back' and url != 'forward': |
| 292 | + if current_index < len(url_stack) - 1: |
| 293 | + url_stack = url_stack[:current_index + 1] # Clear forward if navigation has occurred. |
| 294 | + url_stack.append(url) |
| 295 | + current_index += 1 |
| 296 | + log('Location:', url) |
| 297 | + elif url == 'back': |
| 298 | + back() |
| 299 | + elif url == 'forward': |
| 300 | + forward() |
| 301 | + |
| 302 | +# Simulating browsing |
| 303 | +browse_web('www.lectura_prospectiva.net') # Location: www.lectura_prospectiva.net |
| 304 | +browse_web('www.test.web') # Location: www.test.web |
| 305 | +browse_web('back') # Location: www.lectura_prospectiva.net |
| 306 | +browse_web('forward') # Location: www.test.web |
| 307 | + |
| 308 | +# Simulating a simple UI setup (console-based) |
| 309 | +def setup_ui(): |
| 310 | + log('Retosparaprogramadores #7.') |
| 311 | + |
| 312 | +# Call the UI setup function |
| 313 | +setup_ui() |
| 314 | + |
0 commit comments