0% found this document useful (0 votes)
18 views12 pages

Python Data Structures and SQL Queries

Uploaded by

Bishwajit Salam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views12 pages

Python Data Structures and SQL Queries

Uploaded by

Bishwajit Salam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

A Python program to implement a stack

class Stack:

def __init__(self):

[Link] = []

def is_empty(self):

return len([Link]) == 0

def push(self, item):

[Link](item)

def pop(self):

if not self.is_empty():

return [Link]()

else:

print("Stack is empty. Cannot pop from an empty stack.")

def peek(self):

if not self.is_empty():

return [Link][-1]

else:

print("Stack is empty. Cannot peek into an empty stack.")

def size(self):

return len([Link])

# Example Usage:

my_stack = Stack()

my_stack.push(1)

my_stack.push(2)

my_stack.push(3)

print("Current Stack:", my_stack.items)

print("Top Element:", my_stack.peek())


print("Stack Size:", my_stack.size())

popped_item = my_stack.pop()

print("Popped Item:", popped_item)

print("Updated Stack:", my_stack.items)

Output:

Current Stack: [1, 2, 3]

Top Element: 3

Stack Size: 3

Popped Item: 3

Updated Stack: [1, 2]


A python program to implement a queue

class Queue:

def __init__(self):

[Link] = []

def is_empty(self):

return len([Link]) == 0

def enqueue(self, item):

[Link](item)

def dequeue(self):

if not self.is_empty():

return [Link](0)

else:

print("Queue is empty. Cannot dequeue from an empty queue.")

def front(self):

if not self.is_empty():

return [Link][0]

else:

print("Queue is empty. Cannot get front of an empty queue.")

def size(self):

return len([Link])

# Example Usage:

my_queue = Queue()

my_queue.enqueue(1)

my_queue.enqueue(2)

my_queue.enqueue(3)
print("Current Queue:", my_queue.items)

print("Front Element:", my_queue.front())

print("Queue Size:", my_queue.size())

dequeued_item = my_queue.dequeue()

print("Dequeued Item:", dequeued_item)

print("Updated Queue:", my_queue.items)

output:
A python program to implement a deque

class Deque:

def __init__(self):

[Link] = []

def is_empty(self):

return len([Link]) == 0

def add_front(self, item):

[Link](0, item)

def add_rear(self, item):

[Link](item)

def remove_front(self):

if not self.is_empty():

return [Link](0)

else:

print("Deque is empty. Cannot remove from the front of an empty deque.")

def remove_rear(self):

if not self.is_empty():

return [Link]()

else:

print("Deque is empty. Cannot remove from the rear of an empty deque.")

def front(self):

if not self.is_empty():

return [Link][0]

else:

print("Deque is empty. Cannot get front of an empty deque.")

def rear(self):

if not self.is_empty():

return [Link][-1]

else:

print("Deque is empty. Cannot get rear of an empty deque.")

def size(self):

return len([Link])
# Example Usage:

my_deque = Deque()

my_deque.add_front(1)

my_deque.add_rear(2)

my_deque.add_rear(3)

print("Current Deque:", my_deque.items)

print("Front Element:", my_deque.front())

print("Rear Element:", my_deque.rear())

print("Deque Size:", my_deque.size())

removed_front = my_deque.remove_front()

print("Removed Front Element:", removed_front)

removed_rear = my_deque.remove_rear()

print("Removed Rear Element:", removed_rear)

print("Updated Deque:", my_deque.items)

Output:

Current Deque: [1, 2, 3]

Front Element: 1

Rear Element: 3

Deque Size: 3

Removed Front Element: 1

Removed Rear Element: 3

Updated Deque: [2]


python program to evaluate a postfix expression using a stack.

def evaluate_postfix(expression):

stack = []

def is_operand(char):

return [Link]()

def apply_operator(operator, operand1, operand2):

if operator == '+':

return operand1 + operand2

elif operator == '-':

return operand1 - operand2

elif operator == '*':

return operand1 * operand2

elif operator == '/':

return operand1 / operand2

elif operator == '^':

return operand1 ** operand2

for char in expression:

if is_operand(char):

[Link](int(char))

else:

operand2 = [Link]()

operand1 = [Link]()

result = apply_operator(char, operand1, operand2)

[Link](result)

if len(stack) == 1:

return stack[0]

else:

print("Invalid postfix expression. More than one value left in the stack.")
# Example Usage:

postfix_expression = "235*+"

result = evaluate_postfix(postfix_expression)

print(f"Result of {postfix_expression} is: {result}")

Output:

Result of 235*+ is: 17


a python code to sort a list in ascending order using bubble sort

def bubble_sort(arr):

n = len(arr)

# Traverse through all array elements

for i in range(n):

# Last i elements are already sorted, so we don't need to check them

for j in range(0, n - i - 1):

# Swap if the element found is greater than the next element

if arr[j] > arr[j + 1]:

arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Example Usage:

my_list = [64, 25, 12, 22, 11]

print("Original List:", my_list)

bubble_sort(my_list)

print("Sorted List:", my_list)

output:

Original List: [64, 25, 12, 22, 11]

Sorted List: [11, 12, 22, 25, 64]


a python program to open a file “[Link]” in write mode and write the following lines. open the same file in read
mode to display the contents.

“COUNCIL OF HIGHER SECONDARY EDUCATION MANIPUR”

# Open the file in write mode and write the line

with open("[Link]", "w") as file:

[Link]("COUNCIL OF HIGHER SECONDARY EDUCATION MANIPUR")

# Open the file in read mode and display its contents

with open("[Link]", "r") as file:

contents = [Link]()

print("Contents of '[Link]':")

print(contents)

OUTPUT:

Contents of '[Link]':

COUNCIL OF HIGHER SECONDARY EDUCATION MANIPUR


Consider the table STUDENT and write the SQL commands for the following questions based on it :

[Link] NAME STREAM STIPEND AGE SEX


1 RAKESH COMMERCE 2000 20 M
2 BEENA MEDICAL 2500 22 F
3 AMITA HUMANITIES 2200 21 F
4 AMARJIT SCIENCE 2400 23 M
5 KIRAN MEDICAL 2100 24 M
6 DIANA MEDICAL 2800 22 F
7 LOREN SCIENCE 2400 21 M
8 ROGER COMMERCE 2600 25 M
9 DENIAL HUMANITIES 2500 26 M
10 HENERITA MEDICAL 3000 25 F

(a) To display all the information of male student


(b) Display NAME,STREAM and STIPEND of female students.
(c) List all the students whose name starts with “D”.
(d) List the names of the students having the stream commerce and science.
(e) Display the total stipend of male student.
(f) List all the students in descending order of their stipend.
(g) Count the number of students in MEDICAL stream.
(h) To insert a new row in the table with the values.
11,”JOHN”,”SCIENCE”,2700,24,”M”
(a)To display all the information of male students:
SELECT * FROM STUDENT WHERE SEX = 'M';
Output:
SL_no | NAME | STREAM | STIPEND | AGE | SEX
------+-----------+-------------+---------+-----+-----
1 | RAKESH | COMMERCE | 2000 | 20 | M
4 | AMARJIT | SCIENCE | 2400 | 23 | M
5 | KIRAN | MEDICAL | 2100 | 24 | M
7 | LOREN | SCIENCE | 2400 | 21 | M
8 | ROGER | COMMERCE | 2600 | 25 | M
9 | DENIAL | HUMANITIES | 2500 | 26 | M
11 | JOHN | SCIENCE | 2700 | 24 | M
(b) Display NAME, STREAM, and STIPEND of female students:
SELECT NAME, STREAM, STIPEND FROM STUDENT WHERE SEX = 'F';
Output: NAME | STREAM | STIPEND
-----------+-------------+---------
BEENA | MEDICAL | 2500
AMITA | HUMANITIES | 2200
DIANA | MEDICAL | 2800
HENERITA | MEDICAL | 3000
(c) List all the students whose name starts with “D”:
SELECT * FROM STUDENT WHERE NAME LIKE 'D%';

Output: SL_no | NAME | STREAM | STIPEND | AGE | SEX


------+-----------+-------------+---------+-----+-----
6 | DIANA | MEDICAL | 2800 | 22 | F
9 | DENIAL | HUMANITIES | 2500 | 26 | M
(d) List the names of the students having the stream commerce and
science:
SELECT NAME FROM STUDENT WHERE STREAM IN ('COMMERCE', 'SCIENCE');

Output: NAME
-----
RAKESH
AMARJIT
LOREN
ROGER
JOHN
(e)Display the total stipend of male students:
SELECT SUM(STIPEND) AS TotalStipend FROM STUDENT WHERE SEX = 'M';

output: TotalStipend
-------------
14700
(f) List all the students in descending order of their stipend:
SELECT * FROM STUDENT ORDER BY STIPEND DESC;

Output: SL_no | NAME | STREAM | STIPEND | AGE | SEX


------+-----------+-------------+---------+-----+-----
10 | HENERITA | MEDICAL | 3000 | 25 | F
6 | DIANA | MEDICAL | 2800 | 22 | F
8 | ROGER | COMMERCE | 2600 | 25 | M
11 | JOHN | SCIENCE | 2700 | 24 | M
2 | BEENA | MEDICAL | 2500 | 22 | F
9 | DENIAL | HUMANITIES | 2500 | 26 | M
4 | AMARJIT | SCIENCE | 2400 | 23 | M
7 | LOREN | SCIENCE | 2400 | 21 | M
3 | AMITA | HUMANITIES | 2200 | 21 | F
5 | KIRAN | MEDICAL | 2100 | 24 | M
1 | RAKESH | COMMERCE | 2000 | 20 | M
(g) Count the number of students in MEDICAL stream:
SELECT COUNT(*) AS MedicalStudentsCount FROM STUDENT WHERE STREAM = 'MEDICAL';

Output:
MedicalStudentsCount
---------------------
4

(h) To insert a new row in the table with the values. 11, "JOHN", "SCIENCE",
2700, 24, "M":
INSERT INTO STUDENT (SL_no, NAME, STREAM, STIPEND, AGE, SEX) VALUES (11, 'JOHN', 'SCIENCE', 2700, 24,
'M');

Common questions

Powered by AI

To retrieve a list of students whose stipends are greater than 2500, the SQL query can be written as: SELECT * FROM STUDENT WHERE STIPEND > 2500. This query selects all columns from the 'STUDENT' table where the value in the 'STIPEND' column exceeds 2500. The WHERE clause is used for filtering records based on a specified condition, thereby returning only those rows that fulfill the 'STIPEND > 2500' condition .

The significance of the sorting algorithm's complexity, specifically bubble sort's O(n^2) time complexity, lies in its impact on performance. For lists of small size, bubble sort may perform adequately. However, as the size of the list grows, the algorithm's quadratic complexity results in a rapid deterioration of performance, making it inefficient for large datasets. In the bubble sort provided, each pair of adjacent elements requires comparison and potential swapping across multiple passes of the list, leading to n^2 operations in the worst-case scenario, thus affecting both speed and resource usage unfavorably for substantial inputs .

The stack implementation prevents underflow during a pop operation by first checking if the stack is empty using the is_empty method. If the stack is not empty, the pop operation proceeds by removing and returning the last element of the list. If the stack is empty, it outputs a message stating "Stack is empty. Cannot pop from an empty stack." This condition avoids accessing the stack when there are no elements to pop .

The 'is_empty' check is essential in the implementations of stack, queue, and deque to prevent operations that require elements from proceeding when there are none available to process. For instance, attempting to pop from an empty stack or dequeue from an empty queue can lead to runtime errors due to accessing elements from an empty list, which might result in an IndexError in Python. The presence of this check ensures that the programs maintain stability and provide appropriate feedback to the user instead of crashing .

The sorting algorithm used in the provided Python code is Bubble Sort. It operates by repeatedly passing through the list, comparing adjacent elements and swapping them if they are in the wrong order. This is continued until the entire list is sorted. For each pass through the list, the algorithm reduces the number of elements to consider, as the largest elements gradually "bubble up" to their correct position at the end of the list. The outer loop tracks the number of passes, and the inner loop performs the element comparisons and swaps .

Using a stack versus a queue for evaluating expressions has different implications for calculators and parsers. Stacks are ideal for handling expression evaluations, such as postfix expressions, due to their LIFO nature, which aligns with the need for nested or grouped operations. This is crucial in calculators and parsers to reverse the operations' sequence as typically found in infix to postfix transformations. Queues, with FIFO order, are less suited for expression evaluation directly but are useful in parsing-related tasks when processing tokens in sequential order, such as breadth-first search algorithms used in syntax tree construction. For expression evaluation specifically, the stack ensures correct application of operators by re-evaluating using the precisely needed latest operands .

A deque (double-ended queue) offers greater flexibility over a standard queue or stack by allowing elements to be added or removed from both ends. This capability is beneficial in scenarios requiring elements to be processed from both ends efficiently, like in certain caching algorithms or the sliding window algorithm used in dynamic programming and data streaming. The provided Python deque implementation supports this by providing methods like add_front and remove_rear, which are not present in either the stack or queue classes .

The 'apply_operator' function is crucial for evaluating a postfix expression as it performs the operations indicated by operators on operands that are popped from the stack. During the evaluation process, when an operator is encountered in the postfix expression, 'apply_operator' applies this operator to the two most recent operands popped from the stack. The result of this operation is then pushed back onto the stack. This function ensures that operators are applied correctly in the order defined by postfix notation, thereby directly contributing to obtaining the correct final result of the expression, exemplified by operations such as addition, subtraction, multiplication, division, and exponentiation .

The SQL command structure enables data insertion and retrieval from the 'STUDENT' table through syntax that includes INSERT and SELECT statements. For inserting data, the INSERT INTO statement specifies the table and values for each column, as seen in: INSERT INTO STUDENT (columns) VALUES (values), ensuring provided values match the column order . Retrieval uses SELECT, possibly combined with WHERE or ORDER BY clauses, to filter and sort results, such as SELECT * FROM STUDENT WHERE conditions for specific fetch needs. Essential components include the table name, column names, values, filtering (WHERE), and ordering (ORDER BY) to properly handle table operations .

The main difference between stack and queue data structures lies in their handling of elements: a stack follows Last In First Out (LIFO) principle whereas a queue follows First In First Out (FIFO) principle. In the Python programs provided, this is implemented in two ways: the stack uses the append() method to add elements, and the pop() method without any arguments to remove elements from the end, maintaining LIFO order. In contrast, the queue uses append() to add elements but pop(0) to remove elements from the beginning, ensuring FIFO order .

You might also like