0% found this document useful (0 votes)
2 views8 pages

Python Assignment

The document contains multiple Python programs demonstrating various algorithms and data structures, including linear search, binary search, stack, queue, bubble sort, finding max/min sums in a list of lists, checking for unique elements, and merge sort. Each program includes code snippets and example usage to illustrate the functionality. The programs cover fundamental concepts in programming and data manipulation.

Uploaded by

abhijitdascom5
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)
2 views8 pages

Python Assignment

The document contains multiple Python programs demonstrating various algorithms and data structures, including linear search, binary search, stack, queue, bubble sort, finding max/min sums in a list of lists, checking for unique elements, and merge sort. Each program includes code snippets and example usage to illustrate the functionality. The programs cover fundamental concepts in programming and data manipulation.

Uploaded by

abhijitdascom5
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

[Link] a Python program to find an element in a list (Linear Search).

CODE:-

def linear_search(arr, target):

for i in range(len(arr)):

if arr[i] == target:

return i

return -1

my_list = [5, 3, 8, 6, 2, 7, 4]

element_to_find = 6

result = linear_search(my_list, element_to_find)

if result != -1:

print(f"Element {element_to_find} found at index {result}")

else:

print(f"Element {element_to_find} not found in the list")

2. Write a Python program to find an element in a list using Binary Search.

CODE:-

def binary_search(arr, target):

low = 0

high = len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

low = mid + 1

else:

high = mid - 1

return -1
sorted_list = [2, 4, 6, 8, 10, 12, 14, 16]

element_to_find = 10

result = binary_search(sorted_list, element_to_find)

if result != -1:

print(f"Element {element_to_find} found at index {result}")

else:

print(f"Element {element_to_find} not found in the list")

3. Write a Python program to implement stack with basic operations like insertion, deletion and
display.

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 from an empty stack.")

def peek(self):

if not self.is_empty():

return [Link][-1]
else:

print("Stack is empty. No elements to peek.")

def display(self):

if not self.is_empty():

print("Stack elements:")

for item in reversed([Link]):

print(item)

else:

print("Stack is empty. No elements to display.")

stack = Stack()

[Link](10)

[Link](20)

[Link](30)

[Link]()

print("Popping an element from the stack:", [Link]())

[Link]()

print("Peek element:", [Link]())

[Link]()

print("Popping all elements from the stack:")

while not stack.is_empty():

print("Popped element:", [Link]())

[Link]()
4. Write a Python program to implement queue with basic operations like insertion, deletion and
display.

CODE:

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 peek(self):

if not self.is_empty():

return [Link][0]

else:

print("Queue is empty. No elements to peek.")

def display(self):

if not self.is_empty():

print("Queue elements:")

for item in [Link]:

print(item)

else:
print("Queue is empty. No elements to display.")

# Example usage:

queue = Queue()

[Link](10)

[Link](20)

[Link](30)

[Link]()

print("Dequeueing an element from the queue:", [Link]())

[Link]()

print("Peek element:", [Link]())

[Link]()

print("Dequeueing all elements from the queue:")

while not queue.is_empty():

print("Dequeued element:", [Link]())

[Link]()

5. Write a Python Program to sort a list or tuple without either importing and library or any library
sorting function.

CODE:

def bubble_sort(data):

n = len(data)

for i in range(n):
# Flag to check if any swapping is done in this pass

swapped = False

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

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

# Swap elements if they are in the wrong order

data[j], data[j+1] = data[j+1], data[j]

swapped = True

# If no swapping is done in a pass, the list is already sorted

if not swapped:

break

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

bubble_sort(my_list)

print("Sorted list:", my_list)

6. Maximum and minimum sum of elements of list in a list of lists without using max() or min()
method.

CODE:

def find_max_min_sum(list_of_lists):

if not list_of_lists:

return None, None # Return None for both max and min sums if the list is empty

max_sum = float('-inf') # Initialize max_sum to negative infinity

min_sum = float('inf') # Initialize min_sum to positive infinity

for sublist in list_of_lists:

sublist_sum = sum(sublist)

if sublist_sum > max_sum:

max_sum = sublist_sum

if sublist_sum < min_sum:

min_sum = sublist_sum
return max_sum, min_sum

# Example usage:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

max_sum, min_sum = find_max_min_sum(list_of_lists)

print("Maximum sum of elements in the list of lists:", max_sum)

print("Minimum sum of elements in the list of lists:", min_sum)

7. Check if a list contains all unique elements.

CODE:

def check_unique_elements(my_list):

return len(my_list) == len(set(my_list))

# Example usage:

list1 = [1, 2, 3, 4, 5]

list2 = [1, 2, 2, 3, 4]

print("List 1 contains all unique elements:", check_unique_elements(list1))

print("List 2 contains all unique elements:", check_unique_elements(list2))

8. Write a Python program to sort a list using Merge Sort.

CODE:

def merge_sort(arr):

if len(arr) > 1:

mid = len(arr) // 2

left_half = arr[:mid]

right_half = arr[mid:]

merge_sort(left_half)

merge_sort(right_half)
i=j=k=0

while i < len(left_half) and j < len(right_half):

if left_half[i] < right_half[j]:

arr[k] = left_half[i]

i += 1

else:

arr[k] = right_half[j]

j += 1

k += 1

while i < len(left_half):

arr[k] = left_half[i]

i += 1

k += 1

while j < len(right_half):

arr[k] = right_half[j]

j += 1

k += 1

# Example usage:

my_list = [38, 27, 43, 3, 9, 82, 10]

print("Original list:", my_list)

merge_sort(my_list)

print("Sorted list using Merge Sort:", my_list)

You might also like