Data Structure With Python
Data Structure With Python
LAB MANUAL
Solve:-
With the array module, you can concatenate, or join, arrays using the + operator
and you can add elements to an array using the append(), extend(),
and insert() methods.
Program code:
import array
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('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])
The preceding example creates a new array that contains all the elements of the the
given arrays.
The following example demonstrates how to add to an array using
the append(), extend(), and insert() methods:
import array
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])
print("arr1 is:", arr1)
print("arr2 is:", arr2)
arr1.append(4)
print("\nAfter arr1.append(4), arr1 is:", arr1)
arr1.extend(arr2)
print("\nAfter arr1.extend(arr2), arr1 is:", arr1)
arr1.insert(0, 10)
print("\nAfter arr1.insert(0, 10), arr1 is:", arr1)
Output:
arr1 is: array('i', [1, 2, 3])
arr2 is: array('i', [4, 5, 6])
After arr1.append(4), arr1 is: array('i', [1, 2, 3, 4])
After arr1.extend(arr2), arr1 is: array('i', [1, 2, 3, 4, 4, 5, 6])
After arr1.insert(0, 10), arr1 is: array('i', [10, 1, 2, 3, 4, 4, 5, 6])
remove() - This method removes a certain element from the list. In case of
multiple occurrences of that element, it removes the first occurrence.
pop() - This method removes the element from a certain index from the list.
If no argument is provided this method removes the last element from the
list.
del - del keyword can be used to delete a certain index of an list or the whole
list itself.
clear() - This method can be used to delete all the elements from the list.
Program Code:
lst.clear()
print(lst)
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
print("Stack is empty. Cannot pop.")
return None
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
print("Stack is empty. Cannot peek.")
return None
def size(self):
return len(self.stack)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack:", stack.stack)
print("Peek:", stack.peek())
print("Pop:", stack.pop())
print("Stack:", stack.stack)
print("Is Empty?", stack.is_empty())
print("Stack Size:", stack.size())
class CircularQueue:
def __init__(self, size):
self.maxSize = size
self.queueArray = [0] * size
self.front = -1
self.rear = -1
def dequeue(self):
item = -1 # Assuming -1 represents an empty value
if not self.isEmpty():
item = self.queueArray[self.front]
if self.front == self.rear:
self.front = -1
self.rear = -1
else:
self.front = (self.front + 1) % self.maxSize
else:
print("Queue is empty. Cannot dequeue.")
return item
def peek(self):
if not self.isEmpty():
return self.queueArray[self.front]
else:
print("Queue is empty. No peek value.")
return -1 # Assuming -1 represents an empty value
def isEmpty(self):
return self.front == -1 and self.rear == -1
if __name__ == "__main__":
circularQueue = CircularQueue(5)
circularQueue.enqueue(1)
circularQueue.enqueue(2)
circularQueue.enqueue(3)
# Should print 1
print("Peek:", circularQueue.peek())
# Should print 1
print("Dequeue:", circularQueue.dequeue())
# Should print 2
print("Peek after dequeue:", circularQueue.peek())
def prec(c):
if c == '^':
return 3
return 2
return 1
else:
return -1
Function to perform infix to postfix conversion
def infixToPostfix(s):
st = []
result = ""
for i in range(len(s)):
c = s[i]
if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or (c >= '0' and c <= '9'):
result += c
elif c == '(':
st.append('(')
elif c == ')':
while st[-1] != '(':
result += st.pop()
st.pop()
else:
while st and (prec(c) < prec(st[-1]) or prec(c) == prec(st[-1])):
result += st.pop()
st.append(c)
while st:
result += st.pop()
print(result)
exp = "a+b*(c^d-e)^(f+g*h)-i"
infix To Postfix(exp)
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.
current = head
while current.next:
current = current.next
current.next = new_node
return head
def traverse(head):
current = head
while current:
print(current.data, end=" -> ")
current = current.next
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)
def delete_at_beginning(head):
if head is None:
print("Error: Singly linked list is empty")
return None
new_head = head.next
del head
return new_head
def traverse(head):
current = head
while current:
print(current.data, end=" -> ")
current = current.next
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)
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
linked_list = LinkedList()
linked_list.insert_at_beginning(3)
linked_list.insert_at_beginning(2)
linked_list.insert_at_beginning(1)
class CircularLinkedList:
def __init__(self):
self.head = None
new_node.next = new_node
self.head = new_node
else:
current = self.head
while current.next != self.head:
current = current.next
current.next = new_node
new_node.next = self.head
def delete_at_beginning(self):
if not self.head:
print("Circular Linked List is empty")
return
if self.head.next == self.head:
self.head = None
return
current = self.head
while current.next != self.head:
current = current.next
current.next = self.head.next
self.head = self.head.next
def display(self):
if not self.head:
print("Circular Linked List is empty")
return
current = self.head
while True:
print(current.data, end=" -> ")
current = current.next
if current == self.head:
break
print("", end="")
circular_list = CircularLinkedList()
circular_list.append(1)
circular_list.append(2)
circular_list.append(3)
circular_list.delete_at_beginning()
def display(head):
current = head
while current:
print(current.data, end=" <-> ")
current = current.next
print("None")
head = None
head = insert_at_beginning(head, 3)
head = insert_at_beginning(head, 2)
head = insert_at_beginning(head, 1)
def delete_at_beginning(head):
if head is None:
print("Doubly linked list is empty")
return None
if head.next is None:
return None
new_head = head.next
new_head.prev = None
del head
return new_head
def traverse(head):
current = head
while current:
# Print current node's data
print(current.data, end=" <-> ")
# Move to the next node
current = current.next
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)
Implementation of doubly Circular linked list in data structure:
if head is None:
last = head.prev
newNode.next = head
newNode.prev = last
head.prev = newNode
last.next = newNode
head = newNode
return head
def printList(head):
if not head:
return
curr = head
while True:
print(curr.data, end=" ")
curr = curr.next
if curr == head:
break
print()
head = Node(10)
head.next = Node(20)
head.next.prev = head
head.next.next = Node(30)
head.next.next.prev = head.next
head.next.next.next = head
head.prev = head.next.next
head = insertAtBeginning(head, 5)
printList(head)
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def is_empty(self):
new_node = Node(new_data)
if self.rear is None:
self.front = self.rear = new_node
return
self.rear.next = new_node
self.rear = new_node
def dequeue(self):
if self.is_empty():
print("Queue Underflow")
return
temp = self.front
self.front = self.front.next
if self.front is None:
self.rear = None
def get_front(self):
if self.is_empty():
print("Queue is empty")
return float('-inf')
return self.front.data
def get_rear(self):
if self.is_empty():
print("Queue is empty")
return float('-inf')
return self.rear.data
if __name__ == "__main__":
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.dequeue()
q.dequeue()
q.enqueue(30)
q.enqueue(40)
q.enqueue(50)
q.dequeue()