0% found this document useful (0 votes)
29 views26 pages

Python Pca 2

The document outlines various data structure operations including arrays, stacks, queues, and linked lists, demonstrating insertion, deletion, and traversal methods. It provides code examples for implementing these operations in Python, covering both linear and circular structures. Additionally, it discusses the creation and manipulation of binary search trees and AVL trees.

Uploaded by

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

Python Pca 2

The document outlines various data structure operations including arrays, stacks, queues, and linked lists, demonstrating insertion, deletion, and traversal methods. It provides code examples for implementing these operations in Python, covering both linear and circular structures. Additionally, it discusses the creation and manipulation of binary search trees and AVL trees.

Uploaded by

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

EXPERIMENT NO1:- Implementation of data structure operations (insertion,

deletion, traversing and searching) in array. Linear search and binary search
Solve:-
Inserting an Element to an array using array module
Program code:
import array
arr1 = [Link]('i', [1, 2, 3])
arr2 = [Link]('i', [4, 5, 6]) print("arr1 is:", arr1) print("arr2 is:", arr2)
arr3 = arr1 + arr2
print("After arr3 = arr1 + arr2, arr3 is:", arr3)

Output:
arr1 is: array('i', [1, 2, 3])
arr2 is: array('i', [4, 5, 6])
After arr3 = arr1 + arr2, arr3 is: array('i', [1, 2, 3, 4, 5, 6])

 import array
arr1 = [Link]('i', [1, 2, 3])
arr2 = [Link]('i', [4, 5, 6]) print("arr1 is:", arr1) print("arr2 is:", arr2)
[Link](4)
print("\nAfter [Link](4), arr1 is:", arr1) [Link](arr2)
print("\nAfter [Link](arr2), arr1 is:", arr1) [Link](0, 10)
print("\nAfter [Link](0, 10), arr1 is:", arr1)

Output:
arr1 is: array('i', [1, 2, 3])
arr2 is: array('i', [4, 5, 6])
After [Link](4), arr1 is: array('i', [1, 2, 3, 4])
After [Link](arr2), arr1 is: array('i', [1, 2, 3, 4, 4, 5, 6])
After [Link](0, 10), arr1 is: array('i', [10, 1, 2, 3, 4, 4, 5, 6])

 Deletion an Element to an array using array module:


Program Code:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[Link](2) print(lst) [Link](0) print(lst)
[Link]() print(lst) del lst[0] print(lst) del lst
lst = [1, 2, 3, 4]
print(lst)
[Link]() print(lst)

output
[1, 3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[1, 2, 3, 4]
EXPERIMENT NO2:- Implement of Stack, queue operation using array. Pop,
Push, Insertion, deletion, Implementation of Circular queue. Infix to postfix
expression evaluation. Implementation of stack operations in data structure:

Implementation of stack operations in data structure:


Programme code :
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.")
return None
def peek(self):
if not self.is_empty():
return [Link][-1]
else:
print("Stack is empty. Cannot peek.")
return None

def size(self):
return len([Link])

stack = Stack()
[Link](1)
[Link](2)
[Link](3)

print("Stack:", [Link])
print("Peek:", [Link]())
print("Pop:", [Link]())
print("Stack:", [Link])
print("Is Empty?", stack.is_empty())
print("Stack Size:", [Link]())
output
Stack: [1, 2, 3]
Peek: 3
Pop: 3
Stack: [1, 2]
Is Empty? False
Stack Size: 2

Implementation of circular queue operations in data structure:

class CircularQueue:
def __init__(self, size):
[Link] = size
[Link] = [0] * size
[Link] = -1
[Link] = -1

def enqueue(self, item):


if [Link]():
[Link] = 0
[Link] = 0
[Link][[Link]] = item
else:
[Link] = ([Link] + 1) % [Link]
if [Link] == [Link]:
print("Queue is full. Cannot enqueue.")
[Link] = ([Link] - 1 + [Link]) % [Link]
else:
[Link][[Link]] = item

def dequeue(self):
item = -1 # Assuming -1 represents an empty value

if not [Link]():
item = [Link][[Link]]
if [Link] == [Link]:
[Link] = -1
[Link] = -1
else:
[Link] = ([Link] + 1) % [Link]
else:
print("Queue is empty. Cannot dequeue.")

return item

def peek(self):
if not [Link]():
return [Link][[Link]]
else:
print("Queue is empty. No peek value.")
return -1 # Assuming -1 represents an empty value

def isEmpty(self):
return [Link] == -1 and [Link] == -1

if __name__ == "__main__":
circularQueue = CircularQueue(5)

[Link](1)
[Link](2)
[Link](3)

# Should print 1
print("Peek:", [Link]())

# Should print 1
print("Dequeue:", [Link]())

# Should print 2
print("Peek after dequeue:", [Link]())

output
Peek: 1
Dequeue: 1
Peek after dequeue: 2
EXPERIMENT NO3:- Implementation of linked lists: Single linked list,
circular linked list, double linked list, doubly circular linked list. Implementation
of stack and queue using linked list. Merging two linked list, Linked list
representation of a polynomial, polynomial addition, polynomial multiplication.

Implementation of single linked list in data structure:

 Insertion of linked list


class Node:
def __init__(self, data):
[Link] = data
[Link] = None

def insert_at_beginning(head, data):


new_node = Node(data)
new_node.next = head
return new_node

def insert_at_end(head, data):


new_node = Node(data)
if head is None:
return new_node

current = head
while [Link]:
current = [Link]

[Link] = new_node
return head

def traverse(head):
current = head
while current:
print([Link], end=" -> ")
current = [Link]
print("None")

head = None
head = insert_at_beginning(head, 3)
head = insert_at_beginning(head, 2)
head = insert_at_beginning(head, 1)

insert_at_end(head, 4)
traverse(head)

output
1 -> 2 -> 3 -> 4 -> None

 Deletion of the Single Linked list


class Node:
def __init__(self, data):
[Link] = data
[Link] = None

def insert_at_beginning(head, data):


new_node = Node(data)
new_node.next = head
return new_node

def delete_at_beginning(head):
if head is None:
print("Error: Singly linked list is empty")
return None

new_head = [Link]
del head
return new_head

def traverse(head):
current = head
while current:
print([Link], end=" -> ")
current = [Link]
print("None")

head = None
head = insert_at_beginning(head, 4)
head = insert_at_beginning(head, 3)
head = insert_at_beginning(head, 2)
head = insert_at_beginning(head, 1)

head = delete_at_beginning(head)

traverse(head)

output
2 -> 3 -> 4 -> None

Implementation of the circular linked list in Data Structure:

 Insertion in Circular Linked List:


class Node:
def __init__(self, data):
[Link] = data
[Link] = None

class LinkedList:
def __init__(self):
[Link] = None

def insert_at_beginning(self, data):


new_node = Node(data)
if not [Link]:
[Link] = new_node
new_node.next = [Link]
else:
new_node.next = [Link]
temp = [Link]
while [Link] != [Link]:
temp = [Link]
[Link] = new_node
[Link] = new_node

def display(self):
current = [Link]
while current:
print([Link], end=" -> ")
current = [Link]
print("None")

linked_list = LinkedList()
linked_list.insert_at_beginning(3)
linked_list.insert_at_beginning(2)
linked_list.insert_at_beginning(1)

print("Linked List after insertion at the beginning:")


linked_list.display()

output
Linked List after insertion at the beginning:
1 -> 2 -> 3 -> ... (circular)

Deletion in Circular Linked List:


class Node:
def __init__(self, data):
[Link] = data
[Link] = None

class CircularLinkedList:
def __init__(self):
[Link] = None

def append(self, data):


new_node = Node(data)
if not [Link]:

new_node.next = new_node
[Link] = new_node
else:
current = [Link]
while [Link] != [Link]:
current = [Link]
[Link] = new_node

new_node.next = [Link]

def delete_at_beginning(self):
if not [Link]:
print("Circular Linked List is empty")
return
if [Link] == [Link]:
[Link] = None
return

current = [Link]
while [Link] != [Link]:
current = [Link]

[Link] = [Link]
[Link] = [Link]

def display(self):
if not [Link]:
print("Circular Linked List is empty")
return
current = [Link]
while True:
print([Link], end=" -> ")
current = [Link]
if current == [Link]:
break
print("", end="")

circular_list = CircularLinkedList()
circular_list.append(1)
circular_list.append(2)
circular_list.append(3)

print("Circular Linked List before deletion:")


circular_list.display()
print()

circular_list.delete_at_beginning()

print("Circular Linked List after deletion at the beginning:")


circular_list.display()

output
Circular Linked List before deletion:
1 -> 2 -> 3 ->
Circular Linked List after deletion at the beginning:
2 -> 3 ->
Implementation of double linked list in data structure:

 Insertion of double linked list:


class Node:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None

def insert_at_beginning(head, data):


new_node = Node(data)
new_node.next = head
if head:
[Link] = new_node
return new_node

def display(head):
current = head
while current:
print([Link], end=" <-> ")
current = [Link]
print("None")

head = None
head = insert_at_beginning(head, 3)
head = insert_at_beginning(head, 2)
head = insert_at_beginning(head, 1)

print("Doubly Linked List after insertion at the beginning:")


display(head)

output
Doubly Linked List after insertion at the beginning:
1 <-> 2 <-> 3 <-> None
Deletion of double linked list:
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None

def delete_at_beginning(head):
if head is None:
print("Doubly linked list is empty")
return None

if [Link] is None:
return None

new_head = [Link]
new_head.prev = None
del head
return new_head

def traverse(head):
current = head
while current:
# Print current node's data
print([Link], end=" <-> ")
# Move to the next node
current = [Link]
print("None")

def insert_at_beginning(head, data):


new_node = Node(data)
new_node.next = head
if head:
[Link] = new_node
return new_node

head = None
head = insert_at_beginning(head, 4)
head = insert_at_beginning(head, 3)
head = insert_at_beginning(head, 2)
head = insert_at_beginning(head, 1)
head = delete_at_beginning(head)
traverse(head)

output
1 <-> 2 <-> 3 <-> 4 <-> None

Implementation of doubly Circular linked list in data structure:

Insertion of the Doubly circular linked list:


class Node:
def __init__(self, x):
[Link] = x
[Link] = None
[Link] = None

def insertAtBeginning(head, newData):


newNode = Node(newData)

if head is None:

[Link] = [Link] = newNode


head = newNode
else:

last = [Link]

[Link] = head
[Link] = last
[Link] = newNode
[Link] = newNode

head = newNode

return head

def printList(head):
if not head:
return
curr = head
while True:
print([Link], end=" ")
curr = [Link]
if curr == head:
break
print()

head = Node(10)
[Link] = Node(20)
[Link] = head
[Link] = Node(30)
[Link] = [Link]
[Link] = head
[Link] = [Link]

head = insertAtBeginning(head, 5)
printList(head)

output
5 10 20 30

Implementation of queue using linked list:

class Node:
def __init__(self, new_data):
[Link] = new_data
[Link] = None

class Queue:
def __init__(self):

[Link] = None
[Link] = None

def is_empty(self):

return [Link] is None and [Link] is None

def enqueue(self, new_data):

new_node = Node(new_data)

if [Link] is None:
[Link] = [Link] = new_node
return

[Link] = new_node
[Link] = new_node
def dequeue(self):

if self.is_empty():
print("Queue Underflow")
return

temp = [Link]
[Link] = [Link]

if [Link] is None:
[Link] = None

def get_front(self):

if self.is_empty():
print("Queue is empty")
return float('-inf')
return [Link]

def get_rear(self):

if self.is_empty():
print("Queue is empty")
return float('-inf')
return [Link]

if __name__ == "__main__":
q = Queue()

[Link](10)
[Link](20)

print("Queue Front:", q.get_front())


print("Queue Rear:", q.get_rear())

[Link]()
[Link]()
[Link](30)
[Link](40)
[Link](50)

[Link]()

print("Queue Front:", q.get_front())


print("Queue Rear:", q.get_rear())
output
Queue Front: 10
Queue Rear: 20
Queue Front: 40
Queue Rear: 50

EXPERIMENT 4: Tree: creating Binary Search tree, recursive and non


recursive traversal of BST, deletion in BST, calculating height of a BST, building
AVL tree.

CREATING BINARY SEARCH TREE:


Class BSTNode:
def __init__(self, val=None):
[Link] = None
[Link] = None
[Link] = val

def insert(self, val):


if not [Link]:
[Link] = val
return

if [Link] == val:
return

if val < [Link]:


if [Link]:
[Link](val)
return
[Link] = BSTNode(val)
return

if [Link]:
[Link](val)
return
[Link] = BSTNode(val)

def get_min(self):
current = self
while [Link] is not None:
current = [Link]
return [Link]

def get_max(self):
current = self
while [Link] is not None:
current = [Link]
return [Link]

def delete(self, val):


if self == None:
return self
if [Link] == None:
return [Link]
if [Link] == None:
return [Link]
if val < [Link]:
if [Link]:
[Link] = [Link](val)
return self
if val > [Link]:
if [Link]:
[Link] = [Link](val)
return self
min_larger_node = [Link]
while min_larger_node.left:
min_larger_node = min_larger_node.left
[Link] = min_larger_node.val
[Link] = [Link](min_larger_node.val)
return self

def exists(self, val):


if val == [Link]:
return True

if val < [Link]:


if [Link] == None:
return False
return [Link](val)

if [Link] == None:
return False
return [Link](val)

def preorder(self, vals):


if [Link] is not None:
[Link]([Link])
if [Link] is not None:
[Link](vals)
if [Link] is not None:
[Link](vals)
return vals

def inorder(self, vals):


if [Link] is not None:
[Link](vals)
if [Link] is not None:
[Link]([Link])
if [Link] is not None:
[Link](vals)
return vals

def postorder(self, vals):


if [Link] is not None:
[Link](vals)
if [Link] is not None:
[Link](vals)
if [Link] is not None:
[Link]([Link])
return vals

output
Inorder Traversal: [20, 30, 40, 50, 60, 70, 80]
Preorder Traversal: [50, 30, 20, 40, 70, 60, 80]
Postorder Traversal: [20, 40, 30, 60, 80, 70, 50]
Minimum value: 20
Maximum value: 80
Does 40 exist? True
Does 100 exist? False
Inorder after deleting 20: [30, 40, 50, 60, 70, 80]
DELETION IN BST:
class TreeNode:
def __init__(self, key):
[Link] = key
[Link] = None
[Link] = None

def inorder_traversal(root):
if root:
inorder_traversal([Link])
print([Link], end=" ")
inorder_traversal([Link])

def find_min(node):
current = node
while [Link]:
current = [Link]
return current

def delete_node(root, key):


if root is None:
return root

# Search for the node to be deleted


if key < [Link]:
[Link] = delete_node([Link], key)
elif key > [Link]:
[Link] = delete_node([Link], key)
else:
# Node with only one child or no child
if [Link] is None:
return [Link]
elif [Link] is None:
return [Link]

# Node with two children: Get the in-order successor


temp = find_min([Link])

# Copy the in-order successor's content to this node


[Link] = [Link]

# Delete the in-order successor


[Link] = delete_node([Link], [Link])

return root

if __name__ == "__main__":
root = TreeNode(50)
[Link] = TreeNode(30)
[Link] = TreeNode(70)
[Link] = TreeNode(20)
[Link] = TreeNode(40)
[Link] = TreeNode(60)
[Link] = TreeNode(80)

print("Original BST:")
inorder_traversal(root)
print("\n")

key_to_delete = 40
root = delete_node(root, key_to_delete)

print(f"BST after deleting {key_to_delete}:")


inorder_traversal(root)

output
Original BST:
20 30 40 50 60 70 80

BST after deleting 40:


20 30 50 60 70 80

CALCULATING HEIGHT OF BST:

# define a Class Tree, to intiate the binary tree


class TreeNode:
def __init__(self, val):
[Link] = val
[Link] = None
[Link] = None

def height(root):

# Check if the binary tree is empty


if root is None:
# If TRUE return 0
return 0
# Recursively call height of each node
leftAns = height([Link])
rightAns = height([Link])

# Return max(leftHeight, rightHeight) at each iteration


return max(leftAns, rightAns) + 1

# Test the algorithm


root = TreeNode(1)
[Link] = TreeNode(2)
[Link] = TreeNode(3)
[Link] = TreeNode(4)

print("Height of the binary tree is: " + str(height(root)))

output
Height of the binary tree is: 3

BUILDING AVL TREE:


import sys

# Create a tree node


class TreeNode(object):
def __init__(self, key):
[Link] = key
[Link] = None
[Link] = None
[Link] = 1

class AVLTree(object):

# Function to insert a node


def insert_node(self, root, key):

# Find the correct location and insert the node


if not root:
return TreeNode(key)
elif key < [Link]:
[Link] = self.insert_node([Link], key)
else:
[Link] = self.insert_node([Link], key)

[Link] = 1 + max([Link]([Link]),
[Link]([Link]))

# Update the balance factor and balance the tree


balanceFactor = [Link](root)
if balanceFactor > 1:
if key < [Link]:
return [Link](root)
else:
[Link] = [Link]([Link])
return [Link](root)

if balanceFactor < -1:


if key > [Link]:
return [Link](root)
else:
[Link] = [Link]([Link])
return [Link](root)

return root

# Function to delete a node


def delete_node(self, root, key):

# Find the node to be deleted and remove it


if not root:
return root
elif key < [Link]:
[Link] = self.delete_node([Link], key)
elif key > [Link]:
[Link] = self.delete_node([Link], key)
else:
if [Link] is None:
temp = [Link]
root = None
return temp
elif [Link] is None:
temp = [Link]
root = None
return temp
temp = [Link]([Link])
[Link] = [Link]
[Link] = self.delete_node([Link],
[Link])
if root is None:
return root

# Update the balance factor of nodes


[Link] = 1 + max([Link]([Link]),
[Link]([Link]))

balanceFactor = [Link](root)

# Balance the tree


if balanceFactor > 1:
if [Link]([Link]) >= 0:
return [Link](root)
else:
[Link] = [Link]([Link])
return [Link](root)
if balanceFactor < -1:
if [Link]([Link]) <= 0:
return [Link](root)
else:
[Link] = [Link]([Link])
return [Link](root)
return root

# Function to perform left rotation


def leftRotate(self, z):
y = [Link]
T2 = [Link]
[Link] = z
[Link] = T2
[Link] = 1 + max([Link]([Link]),
[Link]([Link]))
[Link] = 1 + max([Link]([Link]),
[Link]([Link]))
return y

# Function to perform right rotation


def rightRotate(self, z):
y = [Link]
T3 = [Link]
[Link] = z
[Link] = T3
[Link] = 1 + max([Link]([Link]),
[Link]([Link]))
[Link] = 1 + max([Link]([Link]),
[Link]([Link]))
return y

# Get the height of the node


def getHeight(self, root):
if not root:
return 0
return [Link]

# Get balance factore of the node


def getBalance(self, root):
if not root:
return 0
return [Link]([Link]) - [Link]([Link])

def getMinValueNode(self, root):


if root is None or [Link] is None:
return root
return [Link]([Link])

def preOrder(self, root):


if not root:
return
print("{0} ".format([Link]), end="")
[Link]([Link])
[Link]([Link])

# Print the tree


def printHelper(self, currPtr, indent, last):
if currPtr != None:
[Link](indent)
if last:
[Link]("R----")
indent += " "
else:
[Link]("L----")
indent += "| "
print([Link])
[Link]([Link], indent, False)
[Link]([Link], indent, True)

myTree = AVLTree()
root = None
nums = [33, 13, 52, 9, 21, 61, 8, 11]
for num in nums:
root = myTree.insert_node(root, num)
[Link](root, "", True)
key = 13
root = myTree.delete_node(root, key)
print("After Deletion: ")
[Link](root, "", True)

output
R----33
L----13
| L----9
| | L----8
| | R----11
| R----21
R----52
R----61

After Deletion:
R----33
L----9
| L----8
| R----21
| L----11
R----52
R----61
EXPERIMENT 5: Implementation of sorting techniques: selection, bubble,
quick sort, insertion sort, merge sort, heap sot, implementation of priority queue.
Hash table implementation.

SELECTION SORT:
# Selection sort in Python
def selectionSort(array, size):

for step in range(size):


min_idx = step
for i in range(step + 1, size):
# to sort in descending order, change > to < in this line
# select the minimum element in each loop
if array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
(array[step], array[min_idx]) = (array[min_idx], array[step])

data = [-2, 45, 0, 11, -9]


size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)

output
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]

BUBBLE SORT:
# Bubble sort in Python
def bubbleSort(array):

# loop to access each array element


for i in range(len(array)):
# loop to compare array elements
for j in range(0, len(array) - i - 1):
# compare two adjacent elements
# change > to < to sort in descending order
if array[j] > array[j + 1]:
# swapping elements if elements
# are not in the intended order
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print('Sorted Array in Ascending Order:')
print(data)

output
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]

QUICK SORT:
# Quick sort in Python

# function to find the partition position


def partition(array, low, high):

# choose the rightmost element as pivot


pivot = array[high]

# pointer for greater element


i = low - 1

# traverse through all elements


# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# if element smaller than pivot is found
# swap it with the greater element pointed by i
i=i+1

# swapping element at i with element at j


(array[i], array[j]) = (array[j], array[i])

# swap the pivot element with the greater element specified by i


(array[i + 1], array[high]) = (array[high], array[i + 1])

# return the position from where partition is done


return i + 1

# function to perform quicksort


def quickSort(array, low, high):
if low < high:

# find pivot element such that


# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)

# recursive call on the left of pivot


quickSort(array, low, pi - 1)
# recursive call on the right of pivot
quickSort(array, pi + 1, high)

data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)

size = len(data)

quickSort(data, 0, size - 1)

print('Sorted Array in Ascending Order:')


print(data)

output
Unsorted Array
[8, 7, 2, 1, 0, 9, 6]

Sorted Array in Ascending Order:


[0, 1, 2, 6, 7, 8, 9]

INSERTION SORT:
# Insertion sort in Python
def insertionSort(array):

for step in range(1, len(array)):


key = array[step]
j = step - 1
# Compare key with each element on the left of it until an element smaller
than it is found
# For descending order, change key<array[j] to key>array[j].
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j=j-1

# Place key at after the element just smaller than it.


array[j + 1] = key

data = [9, 5, 1, 4, 3]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)

output
Sorted Array in Ascending Order:
[1, 3, 4, 5, 9]

You might also like