Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 10

{

"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Stack and Queue"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Stack\n",
"A stack, also known as a push-down stack, and a last in, first out (LIFO)
stack, is a mutable data structure consisting of a collection of elements that has
(at minimum) two operations defined for it:\n",
"\n",
"push:\n",
"\n",
"Appends an element to a stack.\n",
"\n",
"pop:\n",
"\n",
"Fetches the value of the most recent element pushed onto the stack, and
removes that element from the stack.\n",
"Other operations may include:\n",
"\n",
"top (or peek):\n",
"\n",
"Fetches the value of the most recent element pushed onto the stack. It's like
pop, but doesn't remove the element. Top may be simulated, if it is not defined,
with a pop followed by a push using the same data.\n",
"\n",
"is_empty:\n",
"\n",
"If true, the stack has no elements. This is a handy operation, as it provides
a convenient way to protect against a pop (or top) on an empty stack, but the
stack implementer may choose to use exception handling (try-except in Python 3) to
recover from such disasters instead of doing preemptive testing.\n",
"\n",
"\n",
"size:\n",
"\n",
"Fetches the count of elements currently on the stack.\n",
"\n",
"\n",
"underflow:\n",
"\n",
"The condition that exists when a pop (or top) is attempted on an empty stack.\
n",
"\n",
"overflow:\n",
"\n",
"The condition that exists when a push is attempted on a stack that has
already filled all the memory space allotted to it. \n"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"# An empty stack\n",
"my_stack = []\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"# Push/Add an elemnt to the top of the stack\n",
"def push(stack, element): \n",
" stack.append(element)\n",
"#Anything that can be appended to a list \n",
"#may become an element on the stack."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[5.3, 'fred', 7]\n"
]
}
],
"source": [
"push(my_stack, 5.3) \n",
"push(my_stack, 'fred')\n",
"push(my_stack, 7)\n",
"print(my_stack)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7 [5.3, 'fred']\n"
]
}
],
"source": [
"#Pop and element from the top of the stack\n",
"def pop(stack): \n",
" return stack.pop()\n",
"\n",
"top = my_stack.pop()\n",
"print(top,my_stack)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'fred'"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_stack.pop()"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5.3"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_stack.pop()"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"ename": "IndexError",
"evalue": "pop from empty list",
"output_type": "error",
"traceback": [
"\
u001b[0;31m------------------------------------------------------------------------
---\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m Traceback
(most recent call last)",

"\u001b[0;32m/var/folders/jr/ssd8l3cx7dsc5knynjjc_nzr0000gn/T/ipykernel_7627/421798
9451.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\
u001b[0;31m \u001b[0mmy_stack\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpop\u001b[0m\
u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\
u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m: pop from empty list"
]
}
],
"source": [
"my_stack.pop()"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"def pop(stack): \n",
" try:\n",
" return stack.pop() \n",
" except IndexError:\n",
" print('Error: Stack underflow') \n",
" return None"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Stack underflow\n"
]
}
],
"source": [
"pop(my_stack)"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[5.3, 'fred', 7]\n",
"7 [5.3, 'fred', 7]\n"
]
}
],
"source": [
"def top(stack): \n",
" try:\n",
" return stack[-1] \n",
" except IndexError:\n",
" print('Error: Stack underflow')\n",
"\n",
"push(my_stack, 5.3) \n",
"push(my_stack, 'fred')\n",
"push(my_stack, 7)\n",
"print(my_stack)\n",
"\n",
"item = top(my_stack)\n",
"print(item,my_stack)"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7 [5.3, 'fred']\n"
]
}
],
"source": [
"item = pop(my_stack)\n",
"print(item,my_stack)"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def is_empty(stack): \n",
" return len(stack) == 0\n",
"\n",
"is_empty(my_stack)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def size(stack): \n",
" return len(stack)\n",
"\n",
"size(my_stack)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Queues\n",
"\n",
"A queue, occasionally called a first in, first out (FIFO) stack, is a mutable
data structure consisting of a collection of elements that has (at minimum) two
operations defined for it:\n",
"\n",
"enqueue:\n",
"\n",
"Appends an element to a queue.\n",
"\n",
"dequeue:\n",
"\n",
"Fetches the value of the least recently enqueued element and removes that
element from the queue.\n",
"\n",
"Other operations may include:\n",
"\n",
"front:\n",
"\n",
"Fetches the value of the least recently enqueued element. It's like dequeue
but doesn't remove the element.\n",
"\n",
"is_empty:\n",
"\n",
"This operation on a queue is the same as is_empty for a stack.\n",
"\n",
"size:\n",
"\n",
"Length of the queue\n",
"\n",
"underflow:\n",
"\n",
"The condition that exists when a dequeue (or front) is attempted on an empty
queue.\n",
"\n",
"overflow:\n",
"\n",
"The condition that exists when an enqueue is attempted on a queue that has
already filled all the memory space allotted to it.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"# An empty queue\n",
"my_queue = []"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[4, 3, 2]\n"
]
}
],
"source": [
"def enqueue(queue, element): \n",
" queue.insert(0,element)\n",
"\n",
"enqueue(my_queue,2)\n",
"enqueue(my_queue,3)\n",
"enqueue(my_queue,4)\n",
"print(my_queue)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 [4, 3]\n"
]
}
],
"source": [
"def dequeue(queue): \n",
" return queue.pop()\n",
"\n",
"top = dequeue(my_queue)\n",
"print(top, my_queue)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def is_empty(queue): \n",
" return len(queue) == 0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def size(queue): \n",
" return len(queue)\n",
"\n",
"size(my_queue)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Priority queues"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A priority queue is mostly the same as a regular queue, with a couple of
differences.\n",
"\n",
"Each element in the queue has an accompanying priority value that indicates
its importance.\n",
"\n",
"When an element is enqueued, its priority will cause it to be placed at the
end of the queue only if the element there has an equal or higher priority value.
Otherwise, the insertion will happen at a place in the queue behind the least
recently added element that has the same or greater priority value. If the new
element has a higher priority than any other element in the queue, it will end up
at the front of the queue.\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"After enqueue operations: [(1, 'task3'), (2, 'task2'), (3, 'task1')]\n",
"Dequeued item: task3\n",
"Dequeued item: task2\n",
"Priority queue after dequeue operations: [(3, 'task1')]\n"
]
}
],
"source": [
"priority_queue = []\n",
"\n",
"def enqueue(priority_queue,item, priority):\n",
" # Create a new entry as a tuple of the item and its priority\n",
" new_entry = (priority, item)\n",
" # Append the new entry to the priority queue\n",
" priority_queue.append(new_entry)\n",
" # Sort the priority queue based on priority values\n",
" priority_queue.sort()\n",
"\n",
"\n",
"def dequeue(priority_queue):\n",
"\n",
" if priority_queue:\n",
" # Pop the first element in the sorted list, which has the highest
priority\n",
" _, item = priority_queue.pop(0)\n",
" return item\n",
" else:\n",
" print(\"The priority queue is empty\")\n",
" return None\n",
"\n",
"# Example usage\n",
"enqueue('task1', 3)\n",
"enqueue('task2', 2)\n",
"enqueue('task3', 1)\n",
"\n",
"print(\"After enqueue operations:\", priority_queue)\n",
"\n",
"print(\"Dequeued item:\", dequeue())\n",
"print(\"Dequeued item:\", dequeue())\n",
"print(\"Priority queue after dequeue operations:\", priority_queue)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

You might also like