0% found this document useful (0 votes)
11 views

Lab3

Uploaded by

Alex Siryani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Lab3

Uploaded by

Alex Siryani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

🤖

Lab3:Stack and Queue


Stack Data Structure

Definition
A Stack follows the Last In, First Out (LIFO) principle.

Operations:

Push: Adds an element to the top of the stack.

Pop: Removes the top element from the stack.

# Stack Implementation Using List

# Create a Stack
def create_stack():
stack = []
return stack

# Check if Stack is Empty


def check_empty(stack):
return len(stack) == 0

Lab3:Stack and Queue 1


# Push Operation
def push(stack, item):
stack.append(item)
print("pushed item: " + item)

# Pop Operation
def pop(stack):
if check_empty(stack):
return "stack is empty"
return stack.pop()

# Testing the Stack


stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("----------------------")
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))

Output:
pushed item: 1
pushed item: 2
pushed item: 3
pushed item: 4
----------------------
popped item: 4
stack after popping an element: ['1', '2', '3']

Explanation
1. create_stack() :

Initializes an empty list to represent the stack.

2. check_empty(stack) :

Lab3:Stack and Queue 2


Checks if the stack is empty by evaluating len(stack) == 0 .

3. push(stack, item) :

Adds the item to the top of the stack using the append() method.

4. pop(stack) :

Removes the top item from the stack using pop() .

If the stack is empty, returns "stack is empty."

import queue

# Define a stack using LifoQueue


stack2 = queue.LifoQueue()

# Push items to the stack


stack2.put(10)
stack2.put(5)
stack2.put(18)
stack2.put(1)
stack2.put(9)

# Pop items from the stack


while not stack2.empty():
print("popped item: ", stack2.get())

Output:
popped item: 9
popped item: 1
popped item: 18
popped item: 5
popped item: 10

Explanation

Lab3:Stack and Queue 3


1. LifoQueue :

A built-in Python module that provides stack functionality.

2. put(item) :

Pushes an item onto the stack.

3. get() :

Pops the top item off the stack.

Queue Data Structure

Definition
A Queue follows the First In, First Out (FIFO) principle.

Operations:

Enqueue: Adds an element to the end of the queue.

Dequeue: Removes the front element from the queue.

# Queue Implementation Using List

# Create a Queue
def create_queue():
queue = []
return queue

# Check if Queue is Empty


def check_empty(queue):
return len(queue) == 0

# Enqueue Operation
def push(queue, item):
queue.append(item)
print("pushed item: " + item)

Lab3:Stack and Queue 4


# Dequeue Operation
def pop(queue):
if check_empty(queue):
return "queue is empty"
return queue.pop(0)

# Testing the Queue


queue = create_queue()
push(queue, str(1))
push(queue, str(2))
push(queue, str(3))
push(queue, str(4))
print("----------------------")
print("popped item: " + pop(queue))
print("queue after popping an element: " + str(queue))

Output:
pushed item: 1
pushed item: 2
pushed item: 3
pushed item: 4
----------------------
popped item: 1
queue after popping an element: ['2', '3', '4']

Explanation
1. create_queue() :

Initializes an empty list to represent the queue.

2. check_empty(queue) :

Checks if the queue is empty by evaluating len(queue) == 0 .

3. push(queue, item) :

Adds the item to the end of the queue using the append() method.

Lab3:Stack and Queue 5


4. pop(queue) :

Removes the front item from the queue using pop(0) .

If the queue is empty, returns "queue is empty."

import queue

# Define a Queue using Queue()


queue2 = queue.Queue()

# Enqueue items
queue2.put(10)
queue2.put(5)
queue2.put(18)
queue2.put(1)
queue2.put(9)

# Dequeue items
while not queue2.empty():
print("popped item: ", queue2.get())

Explanation
1. Queue :

A built-in Python module for queue functionality.

2. put(item) :

Adds an item to the end of the queue.

3. get() :

Removes the front item from the queue.

Priority Queue

Lab3:Stack and Queue 6


Definition
A Priority Queue dequeues elements based on their priority.

Higher-priority elements are dequeued first.

class PriorityQueue(object):
def __init__(self):
self.queue = []

def isEmpty(self):
return len(self.queue) == 0

def insert(self, data):


self.queue.append(data)

def delete(self):
try:
max = 0
for i in range(len(self.queue)):
if self.queue[i] > self.queue[max]:
max = i
item = self.queue[max]
del self.queue[max]
return item
except IndexError:
print()
exit()

# Testing the Priority Queue


myQueue = PriorityQueue()
myQueue.insert(12)
myQueue.insert(1)
myQueue.insert(14)
myQueue.insert(7)

while not myQueue.isEmpty():

Lab3:Stack and Queue 7


print("popped item: ", myQueue.delete())

Output:
popped item: 14
popped item: 12
popped item: 7
popped item: 1

Explanation
1. insert(data) :

Adds an element to the queue.

2. delete() :

Finds the highest-priority element (max value) and removes it.

import queue

# Define a Priority Queue using PriorityQueue()


pQueue2 = queue.PriorityQueue()

# Enqueue items with priority


pQueue2.put((1, 10)) # (priority, value)
pQueue2.put((10, 5))
pQueue2.put((2, 18))
pQueue2.put((6, 1))
pQueue2.put((3, 9))

# Dequeue items
while not pQueue2.empty():
print("popped item: ", pQueue2.get())

Output:
popped item: (1, 10)
popped item: (2, 18)

Lab3:Stack and Queue 8


popped item: (3, 9)
popped item: (6, 1)
popped item: (10, 5)

Explanation
1. PriorityQueue :

A built-in Python module for priority queue functionality.

2. put((priority, value)) :

Adds an item with a priority.

3. get() :

Removes the item with the highest priority (lowest priority value).

Lab Solution
Data Structures Exercises

Exercise 1: Storing and Printing Names in Reverse Order

Objective:
Analyze the problem.

Use a stack data structure.

Problem Description:
1. Read 5 names from the user.

2. Store the names in a data structure to facilitate printing them in reverse order.

3. Requirements:

Use a stack, queue, or priority queue.

Do not use the Queue package.

Lab3:Stack and Queue 9


Implement only two functions: push() and pop() .

Justify your selection of the data structure in a comment.

def create_stack():
stack=[]
return stack

def check_empty(stack):
return len(stack)==0

def push(stack,item):
stack.append(item)
print(f'pushed item: {item}')

def pop(stack):
if check_empty(stack):
return 'stack is empty'
return stack.pop()

stack=create_stack()
for i in range(1,6):
name=input(f'enter name {i}: ')
push(stack,name)

print(pop(stack))
print(pop(stack))
print(pop(stack))
print(pop(stack))
print(pop(stack))

Exercise 2: Storing and Printing Names by Length

Objective:
Analyze the problem.

Lab3:Stack and Queue 10


Use a priority queue data structure.

Problem Description:
1. Read 5 names from the user.

2. Store the names in a data structure to facilitate printing them in descending


order of length (longest to shortest).

3. Requirements:

Use a stack, queue, or priority queue.

Use the Queue package.

Justify your selection of the data structure and solution strategy in a


comment.

import queue
Pq=queue.PriorityQueue()

for i in range(1, 6):


name = input(f"Enter name {i}: ")
Pq.put((-len(name), name))

print("\nNames in descending order of length:")


while not Pq.empty():
print(Pq.get()[1])

Exercise 3: DeliveryOrders System

Objective:
Analyze the problem.

Use a queue data structure.

Problem Description:
Develop a class called DeliveryOrders with the following attributes and methods:

Lab3:Stack and Queue 11


Attributes:
1. A data structure to store scheduled orders (use a queue).

2. A list to store delivery types.

3. A variable to count the number of completed orders.

Methods:
1. scheduleDelivery() :

Accepts the delivery and its type.

Adds the delivery to the schedule and its type to the list.

Prints a confirmation message and the number of scheduled orders.

2. completeDelivery() :

Removes the oldest delivery and its type from the schedule.

Updates the count of completed orders.

Prints which delivery was completed.

3. report() :

Prints the total number of scheduled and completed orders.

class DeliveryOrders:
def __init__(self):
self._scheduled_orders = queue.Queue()
self._delivery_types = []
self._completed_orders_count = 0

def scheduleDelivery(self, order, delivery_type):


self._scheduled_orders.put(order)
self._delivery_types.append(delivery_type)
print(f"A new delivery is added to the schedule: {order}
print(f"A total of {self._scheduled_orders.qsize()} are
print("-" * 50)

Lab3:Stack and Queue 12


def completeDelivery(self):
if self._scheduled_orders.empty():
print("No deliveries to complete.")
return
completed_order = self._scheduled_orders.get()
completed_type = self._delivery_types.pop(0)
self._completed_orders_count += 1
print(f"{completed_order} is completed.")
print("-" * 50)

def report(self):
print("Report:")
print(f"A total of {self._scheduled_orders.qsize()} are
print(f"A total of {self._completed_orders_count} are co
print("-" * 50)

orders = DeliveryOrders()

orders.scheduleDelivery("deliver Mashawi", "Food")


orders.scheduleDelivery("deliver Books", "Library")
orders.scheduleDelivery("deliver Mansaf", "Food")
orders.scheduleDelivery("deliver T-Shirt", "Clothes")

orders.report()

orders.completeDelivery()
orders.completeDelivery()

orders.scheduleDelivery("deliver CDs", "Library")

orders.report()

Lab3:Stack and Queue 13

You might also like