1. Write a program to reverse a list without using built-in functions.
Expected Input and
Output: Input: [1, 2, 3, 4, 5] Output: Reversed List: [5, 4, 3, 2, 1]
def reverse_list(list):
reversed_list = []
for i in range(len(list)-1,-1,-1):
reversed_list.append(list[i])
return reversed_list
input_list= [1,2,3,4,5]
output_list= reverse_list(input_list)
print("reversed list:",output_list)
2. Write a program to find the largest and smallest numbers in a list. Expected Input and
Output: Input: [34, 78, 12, 56, 99, 23] Output: Largest: 99 Smallest: 12
def find_largest_smallest(list):
largest=list[0]
smallest=list[0]
for num in list:
if num>largest:
largest=num
if num<smallest:
smallest=num
return largest,smallest
numbers= [34, 78, 12, 56, 99, 23]
largest,smallest=find_largest_smallest(numbers)
print("largest:",largest)
print("smallest:",smallest)
3. Write a program to check if a string is a palindrome. Expected Input and Output: Input:
"radar" Output: 'radar' is a palindrome. Input: "hello" Output: 'hello' is not a palindrome.
def is_palindrome(string):
if string==string[::-1]:
print(f"'{string}' is a palindrome.")
else:
print(f"'{string}' is not a palindrome.")
is_palindrome("radar")
is_palindrome("hello")
4. Write a program to count the frequency of each word in a sentence. Expected Input and
Output: Input: "this is a test this is only a test" Output: Word Frequencies: {'this': 2, 'is':
2, 'a': 2, 'test': 2, 'only': 1}
def word_frequency(sentence):
words=[Link]().split()
frequency={}
for word in words:
frequency[word]=[Link](word,0)+1
return frequency
sentence = "this is a test this is only a test"
print("Word Frequencies:", word_frequency(sentence))
[Link] a program to reverse a string using slicing. Expected Input and Output: Input:
"Python" Output: Reversed String: nohtyP
def reverse_string(string):
return string[::-1]
word="python"
print("reversed string:",reverse_string(word))
6. Write a program to find the union of two sets. Input: set_a = {1, 2, 3}, set_b = {3, 4, 5}
Output: Union of Sets: {1, 2, 3, 4, 5}
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a | set_b
print("Union of Sets:", union_set)
7. Write a program to filter even numbers from a list using list comprehension. Expected
Input and Output: Input: [1, 2, 3, 4, 5, 6] Output: Even Numbers: [2, 4, 6]
list=[1,2,3,4,5,6]
for num in list:
if num%2==0:
print(num)
8. Write a program to count the number of vowels in a string. Expected Input and
Output: Input: "Hello World" Output: Number of Vowels: 3
input_string="hello world"
vowels="aeiouAEIOU"
count=0
for char in input_string:
if char in vowels:
count+=1
print("vowels count:",count)
9. Rotate a list by a given number of positions using slicing. Expected Input and Output:
Input: numbers = [1, 2, 3, 4, 5], positions = 2 Output: Rotated List: [3, 4, 5, 1, 2]
def rotated_list(numbers,position):
return numbers[position:] + numbers[:position]
numbers=[1,2,3,4,5]
position=2
print("rotated list:",rotated_list(numbers,position))
10. Write a program to merge two sorted lists into a single sorted list Expected Input: list1
= [1, 3, 5] list2 = [2, 4, 6] Expected Output: Merged List: [1, 2, 3, 4, 5, 6]
def sorted_list(list1,list2):
return sorted(list1+list2)
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print("sorted list:",sorted_list(list1,list2))
11. Write a program to find the first non-repeating character in a string Expected Input:
"swiss" Expected Output: First Non-Repeating Character: w
def first_non_repeating_character(s):
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
for char in s:
if char_count[char] == 1:
return char
return None
input_string = "swiss"
result = first_non_repeating_character(input_string)
if result:
print(f"First Non-Repeating Character: {result}")
else:
print("No non-repeating character found.")
12. Sum and Product of Tuple Elements Expected Input: (1, 2, 3, 4) Expected Output: Su
m and Product: (10, 24)
def sum_product_tup(tup):
sum_elements=sum(tup)
product_elements=1
for num in tup:
product_elements*=num
return sum_elements ,product_elements
tup=(1,2,3,4)
output=sum_product_tup(tup)
print("sum and product:",output)
13a. Write a program to create an array and display its elements .
def create_and_display_array():
array = [10, 20, 30, 40, 50]
print("Array Elements:")
for element in array:
print(element)
create_and_display_array()
13b. Write a program to sort an array using Quick Sort.
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
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]
return quick_sort(left) + middle + quick_sort(right)
# Example usage
array_to_sort = [34, 7, 23, 32, 5, 62]
sorted_array = quick_sort(array_to_sort)
print("Sorted Array:", sorted_array)
14a. Write a program to insert an element at a given index in an array.
def insert_element(arr, index, element):
if index < 0 or index > len(arr):
print("Index out of bounds.")
return arr
[Link](index, element)
return arr
original_array = [10, 20, 30, 40, 50]
index_to_insert = 2
element_to_insert = 25
modified_array = insert_element(original_array, index_to_insert, element_to_insert)
print("Modified Array:", modified_array)
14b. Write a program to find the square root of a number using Binary Search.
def square_root(number, precision=0.0001):
if number < 0:
raise ValueError("Cannot compute square root of a negative number.")
if number == 0 or number == 1:
return number
start = 0
end = number
mid = 0
while (end - start) > precision:
mid = (start + end) / 2
mid_squared = mid * mid
if mid_squared == number:
return mid
elif mid_squared < number:
start = mid
else:
end = mid
return mid
number_to_find_sqrt = 25
result = square_root(number_to_find_sqrt)
print(f"The square root of {number_to_find_sqrt} is approximately: {result:.4f}")
15a. Write a program to delete an element from a given index in an array.
def delete_element(arr, index):
if index < 0 or index >= len(arr):
print("Index out of bounds.")
return arr
del arr[index]
return arr
original_array = [10, 20, 30, 40, 50]
index_to_delete = 2
modified_array = delete_element(original_array, index_to_delete)
print("Modified Array:", modified_array)
15b. Write a program to sort an array using Bubble Sort.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
array_to_sort = [64, 34, 25, 12, 22, 11, 90]
sorted_array = bubble_sort(array_to_sort)
print("Sorted Array:", sorted_array)
16a. Write a program to find the largest and smallest element in an array.
def find_largest_and_smallest(arr):
if not arr:
return None, None
largest = smallest = arr[0]
for num in arr:
if num > largest:
largest = num
if num < smallest:
smallest = num
return largest, smallest
array = [34, 7, 23, 32, 5, 62]
largest, smallest = find_largest_and_smallest(array)
print(f"Largest Element: {largest}")
print(f"Smallest Element: {smallest}")
16b. Write a program to search for an element in an array using Linear Search.
def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index
return -1
array_to_search = [10, 20, 30, 40, 50]
element_to_find = 30
index_found = linear_search(array_to_search, element_to_find)
if index_found != -1:
print(f"Element {element_to_find} found at index: {index_found}")
else:
print(f"Element {element_to_find} not found in the array.")
17a. Write a program to reverse an array without using extra space.
def reverse_array(arr):
start = 0
end = len(arr) - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
array_to_reverse = [1, 2, 3, 4, 5]
reverse_array(array_to_reverse)
print("Reversed Array:", array_to_reverse)
17b. Write a program to sort an array using Insertion Sort.
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
array_to_sort = [12, 11, 13, 5, 6]
insertion_sort(array_to_sort)
print("Sorted Array:", array_to_sort)
18a. Write a program to search for an element in an array and print its index.
def search_element(arr, target):
for index, element in enumerate(arr):
if element == target:
return index
return -1
array_to_search = [10, 20, 30, 40, 50]
element_to_find = 30
index_found = search_element(array_to_search, element_to_find)
if index_found != -1:
print(f"Element {element_to_find} found at index: {index_found}")
else:
print(f"Element {element_to_find} not found in the array.")
18b. Write a program to merge two sorted arrays using Merge Sort technique.
def merge_sorted_arrays(arr1, arr2):
merged_array = []
i=j=0
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
merged_array.append(arr1[i])
i += 1
else:
merged_array.append(arr2[j])
j += 1
while i < len(arr1):
merged_array.append(arr1[i])
i += 1
while j < len(arr2):
merged_array.append(arr2[j])
j += 1
return merged_array
sorted_array1 = [1, 3, 5, 7]
sorted_array2 = [2, 4, 6, 8]
merged_result = merge_sorted_arrays(sorted_array1, sorted_array2)
print("Merged Sorted Array:", merged_result)
19a. Write a program to find the sum and average of elements in an array.
def calculate_sum_and_average(arr):
if not arr:
return 0, 0.0
total_sum = sum(arr)
average = total_sum / len(arr)
return total_sum, average
array = [10, 20, 30, 40, 50]
total_sum, average = calculate_sum_and_average(array)
print(f"Sum: {total_sum}, Average: {average}")
19b. Write a program to find the first and last occurrence of a given element using Linear
Search.
def find_first_and_last_occurrence(arr, target):
first_index = -1
last_index = -1
for index, element in enumerate(arr):
if element == target:
if first_index == -1:
first_index = index
last_index = index
return first_index, last_index
array_to_search = [1, 2, 3, 2, 4, 2, 5]
element_to_find = 2
first_occurrence, last_occurrence = find_first_and_last_occurrence(array_to_search,
element_to_find)
print(f"First Occurrence of {element_to_find}: {first_occurrence}")
print(f"Last Occurrence of {element_to_find}: {last_occurrence}")
20a. Write a program to copy elements of one array into another array.
def copy_array(source_array):
destination_array = [element for element in source_array]
return destination_array
original_array = [1, 2, 3, 4, 5]
copied_array = copy_array(original_array)
print("Original Array:", original_array)
print("Copied Array:", copied_array)
20b. Write a program to sort an array using Selection Sort.
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
array_to_sort = [64, 25, 12, 22, 11]
selection_sort(array_to_sort)
print("Sorted Array:", array_to_sort)
21a. Write a program to sort an array in ascending and descending order.
def sort_array(arr):
ascending_order = sorted(arr)
descending_order = sorted(arr, reverse=True)
return ascending_order, descending_order
array_to_sort = [64, 25, 12, 22, 11]
ascending, descending = sort_array(array_to_sort)
print("Ascending Order:", ascending)
print("Descending Order:", descending)
21b. Write a program to search for an element in a sorted array using Binary Search.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
sorted_array = [11, 12, 22, 25, 64]
element_to_find = 22
index_found = binary_search(sorted_array, element_to_find)
if index_found != -1:
print(f"Element {element_to_find} found at index: {index_found}")
else:
print(f"Element {element_to_find} not found in the array.")
22a. Write a program to merge two sorted arrays into one sorted array.
def merge_sorted_arrays(arr1, arr2):
merged_array = []
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
merged_array.append(arr1[i])
i += 1
else:
merged_array.append(arr2[j])
j += 1
while i < len(arr1):
merged_array.append(arr1[i])
i += 1
while j < len(arr2):
merged_array.append(arr2[j])
j += 1
return merged_array
sorted_array1 = [1, 3, 5, 7]
sorted_array2 = [2, 4, 6, 8]
merged_result = merge_sorted_arrays(sorted_array1, sorted_array2)
print("Merged Sorted Array:", merged_result)
22b. Write a program to sort an array using Merge Sort.
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
array_to_sort = [38, 27, 43, 3, 9, 82, 10]
merge_sort(array_to_sort)
print("Sorted Array using Merge Sort:", array_to_sort)