Project 1
Project 1
AIM:
     To develop a program in python that finds the sum of all elements in an
array.
PROGRAM:
arr = [1, 2, 3, 4, 5];
sum = 0;
OUTPUT:
Sum of all the elements of an array: 15
  2. FIND A STRING IN AN ARRAY CONSISTING OF CHARACTERS
AIM:
      To develop a program in python that finds a string in an array consisting
of characters.
ALGORITHM:
1. Define a function find_series that takes two parameters: arr (the array of
   characters) and series (the series of characters to find).
2. Use a loop to iterate through the array and check if any subarray of length
   equal to the length of the series matches the given series.
3. If a match is found, return True; otherwise, return False.
PROGRAM:
def find_series(arr, series):
   for i in range(len(arr) - len(series) + 1):
      if arr[i:i+len(series)] == series:
          return True
   return False
RESULT:
  3. FIND THE OCCURRENCE OF A PARTICULAR NUMBER IN AN
                         ARRAY
AIM:
ALGORITHM:
1. Define a function find_occurrence that takes two parameters: arr (the array of
        numbers) and number_to_find (the number whose occurrence needs to be
        found).
2. Initialize a counter variable to 0 to keep track of the occurrences.
3. Use a loop to iterate through the array and increment the counter whenever
        the current element matches the number_to_find.
4. Return the final count of occurrences.
PROGRAM:
def find_occurrence(arr, number_to_find):
  occurrence_count = 0
  for num in arr:
     if num == number_to_find:
        occurrence_count += 1
  return occurrence_count
numbers = [1, 3, 5, 2, 3, 7, 8, 3, 2, 1]
number_to_find = 3
AIM:
         To develop a program in python that identifies the largest element in an
array.
ALGORITHM:
PROGRAM:
def find_largest_element(arr):
  if not arr:
     return None
  max_element = arr[0]
  for num in arr:
     if num > max_element:
          max_element = num
  return max_element
result = find_largest_element(numbers)
print(f"The largest element in the array is: {result}")
OUTPUT:
The largest element in the array is: 42
                  5. PROGRAM FOR ARRAY ROTATION
AIM:
ALGORITHM:
PROGRAM:
def rotate_array(arr, k):
  n = len(arr)
  k=k%n
arr[:k] = reversed(arr[:k])
arr[k:] = reversed(arr[k:])
arr.reverse()
numbers = [1, 2, 3, 4, 5, 6, 7]
rotation_positions = 3
OUTPUT:
Original array: [1, 2, 3, 4, 5, 6, 7]
Array after rotating 3 positions: [5, 6, 7, 1, 2, 3, 4]
  6. PROGRAM TO IMPLEMENT THE OPERATIONS IN A SINGLY
                      LINKED LIST
AIM:
ALGORITHM:
   1. Define a class Node to represent a node in the linked list. Each node has a
      data element and a reference to the next node in the list.
   2. Define a class LinkedList that contains methods to perform operations on
      the linked list:
         o __init__: Initialize an empty linked list.
         o insert_at_end: Insert a new node at the end of the linked list.
         o insert_at_beginning: Insert a new node at the beginning of the
             linked list.
         o delete_node: Delete a node with a given data value from the linked
             list.
         o display: Display the elements of the linked list.
PROGRAM:
class Node:
  def __init__(self, data=None):
    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_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
linked_list.display()
linked_list.insert_at_beginning(0)
linked_list.display()
linked_list.delete_node(2)
linked_list.display()
SAMPLE OUTPUT:
ALGORITHM:
1.       Define a class Node to represent a node in the doubly linked list. Each
         node has a data element, a reference to the next node, and a reference to
         the previous node.
2.       Define a class DoublyLinkedList that contains methods to perform
         operations on the doubly linked list:
            o __init__: Initialize an empty doubly linked list.
            o insert_at_end: Insert a new node at the end of the doubly linked
                list.
            o insert_at_beginning: Insert a new node at the beginning of the
                doubly linked list.
            o delete_node: Delete a node with a given data value from the doubly
                linked list.
            o display_forward: Display the elements of the doubly linked list in
                forward order.
            o display_backward: Display the elements of the doubly linked list in
                backward order.
PROGRAM:
class Node:
     def __init__(self, data=None):
       self.data = data
       self.next = None
       self.prev = None
class DoublyLinkedList:
     def __init__(self):
       self.head = None
  def display_backward(self):
    current = self.head
    while current and current.next:
       current = current.next
    while current:
       print(current.data, end=" <-> ")
       current = current.prev
    print("None")
doubly_linked_list = DoublyLinkedList()
doubly_linked_list.insert_at_end(1)
doubly_linked_list.insert_at_end(2)
doubly_linked_list.insert_at_end(3)
doubly_linked_list.display_forward()
doubly_linked_list.display_backward()
doubly_linked_list.insert_at_beginning(0)
doubly_linked_list.display_forward()
doubly_linked_list.display_backward()
doubly_linked_list.delete_node(2)
doubly_linked_list.display_forward()
doubly_linked_list.display_backward()
SAMPLE OUTPUT:
1 <-> 2 <-> 3 <-> None
3 <-> 2 <-> 1 <-> None
0 <-> 1 <-> 2 <-> 3 <-> None
3 <-> 2 <-> 1 <-> 0 <-> None
0 <-> 1 <-> 3 <-> None
3 <-> 1 <-> 0 <-> None
AIM:
      To develop a program in python that implements a stack data structure
using an array.
ALGORITHM:
PROGRAM:
class Stack:
  def __init__(self):
     self.items = []
  def is_empty(self):
     return len(self.items) == 0
  def pop(self):
     if not self.is_empty():
       return self.items.pop()
     else:
       return "Stack is empty"
  def peek(self):
     if not self.is_empty():
        return self.items[-1]
     else:
        return "Stack is empty"
  def size(self):
     return len(self.items)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
popped_item = stack.pop()
print("Popped item:", popped_item)
OUTPUT:
Top of the stack: 3
Size of the stack: 3
Popped item: 3
Top of the stack after pop: 2
Size of the stack after pop: 2
     9. PROGRAM TO IMPLEMENT STACK USING LINKED LIST
AIM:
ALGORITHM:
   1. Define a class Node to represent a node in the linked list. Each node has a
      data element and a reference to the next node.
   2. Define a class Stack with methods to perform stack operations:
         o __init__: Initialize an empty stack with a head pointing to None.
         o is_empty: Check if the stack is empty.
         o push: Add an element to the top of the stack by creating a new
             node.
         o pop: Remove and return the element from the top of the stack.
         o peek: Return the element at the top of the stack without removing
             it.
         o size: Return the current size of the stack.
PROGRAM:
class Node:
  def __init__(self, data=None):
     self.data = data
     self.next = None
class Stack:
  def __init__(self):
     self.head = None
  def is_empty(self):
     return self.head is None
def push(self, item):
  new_node = Node(item)
  new_node.next = self.head
  self.head = new_node
def pop(self):
  if not self.is_empty():
     popped_item = self.head.data
     self.head = self.head.next
     return popped_item
  else:
     return "Stack is empty"
def peek(self):
  if not self.is_empty():
     return self.head.data
  else:
     return "Stack is empty"
def size(self):
  current = self.head
  count = 0
  while current:
     count += 1
     current = current.next
  return count
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
popped_item = stack.pop()
print("Popped item:", popped_item)
OUTPUT:
Top of the stack: 3
Size of the stack: 3
Popped item: 3
Top of the stack after pop: 2
Size of the stack after pop: 2
ALGORITHM:
PROGRAM:
class Queue:
  def __init__(self):
    self.items = []
  def is_empty(self):
    return len(self.items) == 0
  def dequeue(self):
    if not self.is_empty():
       return self.items.pop(0)
    else:
       return "Queue is empty"
  def peek(self):
     if not self.is_empty():
       return self.items[0]
     else:
       return "Queue is empty"
  def size(self):
     return len(self.items)
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
dequeued_item = queue.dequeue()
print("Dequeued item:", dequeued_item)
OUTPUT:
Front of the queue: 1
Size of the queue: 3
Dequeued item: 1
Front of the queue after dequeue: 2
Size of the queue after dequeue: 2
ALGORITHM:
   1. Define a class Node to represent a node in the linked list. Each node has a
      data element and a reference to the next node.
   2. Define a class Queue with methods to perform queue operations:
         o __init__: Initialize an empty queue with front and rear pointing to
             None.
         o is_empty: Check if the queue is empty.
         o enqueue: Add an element to the rear of the queue by creating a new
             node.
         o dequeue: Remove and return the element from the front of the
             queue.
         o peek: Return the element at the front of the queue without
             removing it.
         o size: Return the current size of the queue.
PROGRAM:
class Node:
   def __init__(self, data=None):
     self.data = data
     self.next = None
class Queue:
   def __init__(self):
     self.front = None
     self.rear = None
  def is_empty(self):
    return self.front is None
  def dequeue(self):
    if not self.is_empty():
       dequeued_item = self.front.data
       self.front = self.front.next
       if self.front is None:
          self.rear = None
       return dequeued_item
    else:
       return "Queue is empty"
  def peek(self):
    if not self.is_empty():
       return self.front.data
    else:
       return "Queue is empty"
  def size(self):
    current = self.front
    count = 0
    while current:
       count += 1
       current = current.next
    return count
# Example usage:
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
dequeued_item = queue.dequeue()
print("Dequeued item:", dequeued_item)
print("Front of the queue after dequeue:", queue.peek())
print("Size of the queue after dequeue:", queue.size())
OUTPUT:
ALGORITHM:
PROGRAM:
class CircularQueue:
   def __init__(self, capacity):
     self.capacity = capacity
     self.queue = [None] * capacity
     self.front = self.rear = -1
     self.size = 0
  def is_empty(self):
    return self.size == 0
  def is_full(self):
    return self.size == self.capacity
    if self.is_empty():
       self.front = self.rear = 0
    else:
       self.rear = (self.rear + 1) % self.capacity
     self.queue[self.rear] = item
     self.size += 1
  def dequeue(self):
    if self.is_empty():
       print("Queue is empty. Cannot dequeue.")
       return None
dequeued_item = self.queue[self.front]
     if self.front == self.rear:
        self.front = self.rear = -1
     else:
        self.front = (self.front + 1) % self.capacity
     self.size -= 1
     return dequeued_item
  def peek(self):
    if self.is_empty():
       print("Queue is empty. Cannot peek.")
       return None
    return self.queue[self.front]
cq = CircularQueue(5)
cq.enqueue(1)
cq.enqueue(2)
cq.enqueue(3)
cq.enqueue(4)
cq.enqueue(5)
cq.enqueue(6)
dequeued_item = cq.dequeue()
print("Dequeued item:", dequeued_item)
OUTPUT:
RESULT:
ALGORITHM:
PROGRAM:
def infix_to_postfix(infix_expression):
  stack = []
  postfix_expression = ""
  precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
  return postfix_expression
infix_expr = "a + b * (c ^ d - e) / f"
postfix_expr = infix_to_postfix(infix_expr)
print("Infix Expression:", infix_expr)
print("Postfix Expression:", postfix_expr)
OUTPUT:
Infix Expression: a + b * (c ^ d - e) / f
Postfix Expression: abcd^e-f*/+
RESULT:
ALGORITHM:
PROGRAM:
from collections import defaultdict
class Graph:
  def __init__(self):
     self.graph = defaultdict(list)
  while queue:
     node = queue.pop(0)
     if node not in visited:
       result_bfs.append(node)
       visited.add(node)
       queue.extend(self.graph[node])
return result_bfs
  visited.add(start)
  result_dfs.append(start)
  return result_dfs
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
start_node = 2
OUTPUT:
RESULT:
AIM:
      To develop a program in python to find a solution to the N-Queens
problem.
ALGORITHM:
PROGRAM:
def is_safe(board, row, col, n):
  for i in range(col):
     if board[row][i] == 1:
       return False
return True
  for i in range(n):
     if is_safe(board, i, col, n):
       board[i][col] = 1
       solve_n_queens_util(board, col + 1, n, solutions)
       board[i][col] = 0 # Backtrack
def solve_n_queens(n):
  board = [[0] * n for _ in range(n)]
  solutions = []
  solve_n_queens_util(board, 0, n, solutions)
  return solutions
def print_solution(solution):
  for row in solution:
     print(' '.join('Q' if cell == 1 else '.' for cell in row))
  print()
OUTPUT:
Enter the value of N for the N-Queens problem: 4
Solutions for N-Queens problem (N = 4):
Solution 1:
.Q..
...Q
Q...
..Q.
Solution 2:
..Q.
Q...
...Q
.Q..
RESULT:
ALGORITHM:
PROGRAM:
class TreeNode:
self.city = city
self.distance = distance
self.left = None
self.right = None
def build_sample_tree():
root = TreeNode("A", 0)
root.left = TreeNode("B", 5)
root.left.left = TreeNode("D", 8)
root.left.right = TreeNode("E", 6)
if not root:
return
path.append(root.city)
current_distance += root.distance
shortest_path[0] = list(path)
shortest_path[1] = current_distance
path.pop()
current_distance -= root.distance
def traveling_salesman_problem(root):
if not root:
     return None
  shortest_path = [None, float('inf')] # [Shortest Path, Shortest Distance]
tree_root = build_sample_tree()
OUTPUT:
Shortest Path: ['A', 'B', 'E', 'C', 'G', 'F', 'D']
Shortest Distance: 36
RESULT:
AIM:
       To develop a program in python that sorts a list of elements using the
Insertion Sort algorithm.
ALGORITHM
   1. Start with the second element (index 1) and compare it with the first
      element.
   2. If the second element is smaller, swap it with the first element.
   3. Move to the third element (index 2) and compare it with the second
      element and then with the first element. Swap if necessary.
   4. Repeat this process for each element in the list until the entire list is
      sorted.
PROGRAM:
def insertion_sort(arr):
  for i in range(1, len(arr)):
     key = arr[i]
     j=i-1
arr[j + 1] = key
RESULT:
ALGORITHM:
   1. Choose a "pivot" element from the array. The choice of the pivot can be
      random, or it can be the middle or the last element.
   2. Partition the array into two sub-arrays: elements less than the pivot and
      elements greater than the pivot.
   3. Recursively apply the Quick Sort algorithm to the two sub-arrays.
   4. Combine the sorted sub-arrays and the pivot to get the final sorted array.
PROGRAM:
def quick_sort(arr):
  if len(arr) <= 1:
     return arr
  pivot = arr[len(arr) // 2]
  left = [x for x in arr if x < pivot]
  middle = [x for x in arr if x == pivot]
  right = [x for x in arr if x > pivot]
AIM:
To develop a program in python to sort a list of elements using the Merge Sort
algorithm.
ALGORITHM:
   1. Divide the unsorted list into n sub-lists, each containing one element (a
      list of one element is considered sorted).
   2. Repeatedly merge sub-lists to produce new sorted sub-lists until there is
      only one sub-list remaining.
PROGRAM:
def merge_sort(arr):
  if len(arr) <= 1:
     return arr
  mid = len(arr) // 2
  left = arr[:mid]
  right = arr[mid:]
  left = merge_sort(left)
  right = merge_sort(right)
  return result
numbers = [12, 4, 5, 6, 7, 3, 1, 15]
OUTPUT:
Original list: [12, 4, 5, 6, 7, 3, 1, 15]
Sorted list: [1, 3, 4, 5, 6, 7, 12, 15]
RESULT:
ALGORITHM:
PROGRAM:
OUTPUT:
Linear Search: Element 16 found at index 4.
RESULTS:
   21.PROGRAM TO FIND AN ELEMENT USING BINARY SEARCH
AIM:
ALGORITHM:
PROGRAM:
def binary_search(arr, target):
  low, high = 0, len(arr) - 1
        if arr[mid] == target:
          return mid
        elif arr[mid] < target:
          low = mid + 1
        else:
          high = mid - 1
  return -1
numbers = [1, 5, 8, 12, 16, 23, 42]
target_element = 16
if index != -1:
  print(f"Binary Search: Element {target_element} found at index {index}.")
else:
  print(f"Binary Search: Element {target_element} not found.")
OUTPUT:
Binary Search: Element 16 found at index 4.
RESULT: