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

Data sct

The document contains multiple Python programs demonstrating various data structures and algorithms, including student information management, stack, queue, circular queue, linked list, ordered linked list, and the Josephus problem. Each program includes class definitions and methods for operations like insertion, deletion, searching, and sorting. The document serves as a comprehensive guide for implementing fundamental data structures in Python.

Uploaded by

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

Data sct

The document contains multiple Python programs demonstrating various data structures and algorithms, including student information management, stack, queue, circular queue, linked list, ordered linked list, and the Josephus problem. Each program includes class definitions and methods for operations like insertion, deletion, searching, and sorting. The document serves as a comprehensive guide for implementing fundamental data structures in Python.

Uploaded by

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

 Write a program which accept informa on about five student and display same

informa on according to ascending order of their name in ?


Ans :- # Define a class to store student informa on
class Student:
def __init__(self, name, age, marks):
self.name = name
self.age = age
self.marks = marks

# Accept informa on for 5 students


students = []
for i in range(5):
print(f"Enter details for student {i+1}:")
name = input("Enter Name: ")
age = int(input("Enter Age: "))
marks = float(input("Enter Marks: "))
students.append(Student(name, age, marks))

# Sort the list by student name


students.sort(key=lambda student: student.name)

# Display sorted student informa on


print("\nStudent details in ascending order of name:")
for student in students:
print(f"Name: {student.name}, Age: {student.age}, Marks: {student.marks}")
This Python program:
1. Collects the name, age, and marks of five students.
2. Stores them in a List<Student>.
3. Sorts the list alphabe cally by student name.
4. Displays the sorted student details.

 Write a program to implement stack ?


Ans :- class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
print(f"{value} pushed onto stack.")
def pop(self):

if self.is_empty():
print("Stack is empty.")
return None
return self.stack.pop()

def peek(self):
if self.is_empty():
print("Stack is empty.")
return None
return self.stack[-1]

def is_empty(self):
return len(self.stack) == 0

# Demonstra on of stack opera ons


if __name__ == "__main__":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)

print("Top element is:", stack.peek())

print("Popped element:", stack.pop())


print("Popped element:", stack.pop())
print("Popped element:", stack.pop())
print("Popped element:", stack.pop()) # A empt to pop from empty stack
I've updated your document to implement a stack using Python. This version includes
push, pop, peek, and is_empty methods, along with a demonstra on.

 Write a program to convert infix expression into pos ix expression?


Ans :- class Stack:
def __init__(self):
self.stack = []

def push(self, value):


self.stack.append(value)

def pop(self):
if self.is_empty():
return None
return self.stack.pop()
def peek(self):
if self.is_empty():
return None
return self.stack[-1]

def is_empty(self):
return len(self.stack) == 0

def precedence(self, op):


if op in ('+', '-'):
return 1
if op in ('*', '/'):
return 2
return 0

def infix_to_pos ix(self, expression):


output = []
operator_stack = Stack()

for char in expression:


if char.isalnum(): # Operand
output.append(char)
elif char == '(':
operator_stack.push(char)
elif char == ')':
while not operator_stack.is_empty() and operator_stack.peek() != '(':
output.append(operator_stack.pop())
operator_stack.pop()
else: # Operator
while (not operator_stack.is_empty() and
self.precedence(operator_stack.peek()) >= self.precedence(char)):
output.append(operator_stack.pop())
operator_stack.push(char)

while not operator_stack.is_empty():


output.append(operator_stack.pop())

return "".join(output)

# Demonstra on of infix to pos ix conversion


if __name__ == "__main__":
stack = Stack()
expression = "a+b*(c^d-e)" # Example infix expression
print("Pos ix expression:", stack.infix_to_pos ix(expression))
I've updated your document to include a Python program that converts an infix
expression to a pos ix expression using a stack

 Write a program to check balanced parentheses for a given infix expression?


Ans :- class Stack:
def __init__(self):
self.stack = []

def push(self, value):


self.stack.append(value)

def pop(self):
if self.is_empty():
return None
return self.stack.pop()

def is_empty(self):
return len(self.stack) == 0

def is_balanced(expression):
stack = Stack()
matching_parentheses = {')': '(', '}': '{', ']': '['}

for char in expression:


if char in '({[':
stack.push(char)
elif char in ')}]':
if stack.is_empty() or stack.pop() != matching_parentheses[char]:
return False

return stack.is_empty()

# Demonstra on of checking balanced parentheses


if __name__ == "__main__":
expression = input("Enter an infix expression: ")
if is_balanced(expression):
print("The expression has balanced parentheses.")
else:
print("The expression has unbalanced parentheses.")

 Write a program to evaluate pos ix expression ?


Ans :- def evaluate_pos ix(expression):
stack = []
operators = {'+', '-', '*', '/'}

for token in expression.split():


if token.isdigit():
stack.append(int(token))
elif token in operators:
operand2 = stack.pop()
operand1 = stack.pop()

if token == '+':
result = operand1 + operand2
elif token == '-':
result = operand1 - operand2
elif token == '*':
result = operand1 * operand2
elif token == '/':
result = operand1 / operand2 # True division

stack.append(result)

return stack.pop()

# Example usage
pos ix_expr = "5 3 2 * + 9 -"
result = evaluate_pos ix(pos ix_expr)
print("Result:", result)
This program uses a stack to evaluate the pos ix expression by itera ng through tokens,
pushing operands onto the stack, and performing opera ons when encountering an
operator.

 Write a program to implement queue ?


Ans:- class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
print(f"Enqueued: {item}")

def dequeue(self):
if self.is_empty():
print("Queue is empty!")
return None
return self.queue.pop(0)

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

def peek(self):
if self.is_empty():
print("Queue is empty!")
return None
return self.queue[0]

def size(self):
return len(self.queue)

# Example usage
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
print("Dequeued:", q.dequeue())
print("Front of queue:", q.peek())
print("Queue size:", q.size())
This program implements a basic queue using a list in Python. It includes opera ons like
enqueue, dequeue, checking if the queue is empty, peeking at the front element, and
ge ng the queue size.

 Write a program to implement circular queue ?


Ans:- class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = self.rear = -1
def is_full(self):
return (self.rear + 1) % self.capacity == self.front

def is_empty(self):
return self.front == -1

def enqueue(self, item):


if self.is_full():
print("Queue is full!")
return

if self.front == -1:
self.front = 0

self.rear = (self.rear + 1) % self.capacity


self.queue[self.rear] = item
print(f"Enqueued: {item}")

def dequeue(self):
if self.is_empty():
print("Queue is empty!")
return None

item = self.queue[self.front]

if self.front == self.rear:
self.front = self.rear = -1
else:
self.front = (self.front + 1) % self.capacity

return item

def peek(self):
if self.is_empty():
print("Queue is empty!")
return None
return self.queue[self.front]

def display(self):
if self.is_empty():
print("Queue is empty!")
return

i = self.front
while True:
print(self.queue[i], end=" ")
if i == self.rear:
break
i = (i + 1) % self.capacity
print()

# Example usage
cq = CircularQueue(5)
cq.enqueue(10)
cq.enqueue(20)
cq.enqueue(30)
cq.enqueue(40)
cq.enqueue(50)
cq.display()
print("Dequeued:", cq.dequeue())
cq.enqueue(60)
cq.display()
This program implements a circular queue using a fixed-size list in Python. It includes
opera ons like enqueue, dequeue, peek, and display while handling wrap-around cases.
 Write a program to implement link list with insert, delete, search, view, and delete
func on ?
Ans :- class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
print(f"Inserted: {data}")

def delete(self, key):


temp = self.head
if temp and temp.data == key:
self.head = temp.next
temp = None
print(f"Deleted: {key}")
return

prev = None
while temp and temp.data != key:
prev = temp
temp = temp.next

if not temp:
print("Key not found!")
return

prev.next = temp.next
temp = None
print(f"Deleted: {key}")

def search(self, key):


temp = self.head
while temp:
if temp.data == key:
print(f"Found: {key}")
return True
temp = temp.next
print("Key not found!")
return False

def view(self):
temp = self.head
if not temp:
print("List is empty!")
return
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")

def delete_list(self):
self.head = None
print("Linked list deleted!")

# Example usage
ll = LinkedList()
ll.insert(10)
ll.insert(20)
ll.insert(30)
ll.view()
ll.search(20)
ll.delete(20)
ll.view()
ll.delete_list()
ll.view()
This program implements a singly linked list in Python with func ons to insert, delete,
search, view, and delete the en re list.

 Write a program to implement ordered link list ?


Ans:- class Node:
def __init__(self, data):
self.data = data
self.next = None

class OrderedLinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)
if not self.head or self.head.data >= data:
new_node.next = self.head
self.head = new_node
else:
temp = self.head
while temp.next and temp.next.data < data:
temp = temp.next
new_node.next = temp.next
temp.next = new_node
print(f"Inserted: {data}")

def delete(self, key):


temp = self.head
if temp and temp.data == key:
self.head = temp.next
temp = None
print(f"Deleted: {key}")
return

prev = None
while temp and temp.data != key:
prev = temp
temp = temp.next

if not temp:
print("Key not found!")
return

prev.next = temp.next
temp = None
print(f"Deleted: {key}")

def search(self, key):


temp = self.head
while temp:
if temp.data == key:
print(f"Found: {key}")
return True
temp = temp.next
print("Key not found!")
return False

def view(self):
temp = self.head
if not temp:
print("List is empty!")
return
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")

def delete_list(self):
self.head = None
print("Ordered linked list deleted!")

# Example usage
oll = OrderedLinkedList()
oll.insert(30)
oll.insert(10)
oll.insert(20)
oll.insert(40)
oll.view()
oll.search(20)
oll.delete(20)
oll.view()
oll.delete_list()
oll.view()
This program implements an ordered linked list in Python, ensuring elements are
inserted in sorted order. It includes func ons to insert, delete, search, view, and delete
the en re list.

 Write a program to implement Joseph problem ?


Ans:- def josephus(n, k):
if n == 1:
return 0
else:
return (josephus(n - 1, k) + k) % n

# Wrapper func on to adjust for 1-based index


def josephus_posi on(n, k):
return josephus(n, k) + 1

# Example usage
n = 7 # Number of people
k = 3 # Step count
print("The safe posi on is:", josephus_posi on(n, k))
This program implements the Josephus problem using recursion, determining the safe
posi on in a circle.

You might also like