Shivansh Ai
Shivansh Ai
Objective:- Write a Program to Implement Recursion of Linear Search & Binary Search using Python.
Step 2 − If the value matches with the key, return the position at which the value was found.
Step 3 − If the value does not match with the key, compare the next element in the array.
Step 4 − Repeat Step 3 until there is a match found. Return the position at which the match was found.
Step 5 − If it is an unsuccessful search, print that the element is not present in the array and exit the program.
IMPLEMENTATION
def linear_search_recursive(arr, target, index=0):
return -1
if arr[index] == target:
return index
try:
if result != -1:
else:
except ValueError:
# Shivansh Mudgal
# 2202301530052
Step 2 − If the middle element is equal to the key, return the index.
Step 3 − If the middle element is greater than the key, search the left half of the array.
Step 4 − If the middle element is less than the key, search the right half of the array.
Step 5 − Repeat the process recursively on the relevant half until the key is found or the interval is
empty.
IMPLEMENTATION
def binary_search_recursive(arr, target, low, high):
return -1
if arr[mid] == target:
return mid
else:
try:
if result != -1:
else:
except ValueError:
# Shivansh Mudgal
# 2202301530052
Remove the front node from the queue and process it.
IMPLEMENTATION
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
visited = []
queue = []
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
# 2202301530052
Step 3 − Repeat the process for every unvisited node until all nodes are visited.
IMPLEMENTATION
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
visited = set()
print(node)
visited.add(node)
# Shivansh Mudgal
# 2202301530052
Objective:- Write a Program in Python for Sorting the Data using Apply Insertion sort.
Step 5 − Repeat steps 2 to 4 for each remaining element in the array until the entire array is sorted.
IMPLEMENTATION
def insertion_sort(arr):
key = arr[i]
j=i-1
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
if __name__ == "__main__":
try:
insertion_sort(arr)
except ValueError:
# Shivansh Mudgal
# 2202301530052
IMPLEMENTATION
def sort_sentence(sentence):
words = sentence.split()
words.sort(key=str.lower)
return sorted_sentence
if __name__ == "__main__":
sorted_sentence = sort_sentence(sentence)
# Shivansh Mudgal
# 2202301530052
TIC-TAC-TOE GAME
ALGORITHM
Step 1 − Display the empty 3x3 board.
Step 2 − Take turns for player 'X' and player 'O' to make their moves.
Step 3 − After each move, check if a player has won or if the game is a draw.
Step 4 − Continue the game until there is a winner or the board is full.
IMPLEMENTATION
import math
def print_board(board):
print(" | ".join(row))
print("-" * 9)
def check_winner(board):
for i in range(3):
return board[i][0]
return board[0][i]
# Check diagonals
return board[0][0]
return board[0][2]
return "Tie"
return None
if winner == "X":
return -1
if winner == "O":
return 1
if winner == "Tie":
return 0
if is_maximizing:
best_score = -math.inf
for i in range(3):
for j in range(3):
board[i][j] = "O"
return best_score
else:
best_score = math.inf
for i in range(3):
for j in range(3):
board[i][j] = "X"
return best_score
def best_move(board):
move = None
for i in range(3):
for j in range(3):
board[i][j] = "O"
best_score = score
move = (i, j)
return move
def tic_tac_toe():
print("Tic-Tac-Toe!")
print_board(board)
while True:
# Player's turn
while True:
try:
user_move = input("Enter your move (row and column: 1 1 for top-left): ")
row -= 1
col -= 1
board[row][col] = "X"
break
else:
print("Invalid input. Please enter row and column as two numbers (e.g., 1 1).")
print_board(board)
result = check_winner(board)
if result:
print("You win!")
print("Computer wins!")
else:
print("It's a tie!")
break
# Computer's turn
print("Computer's turn...")
move = best_move(board)
if move:
board[move[0]][move[1]] = "O"
print_board(board)
result = check_winner(board)
if result:
if result == "X":
print("You win!")
print("Computer wins!")
else:
print("It's a tie!")
break
if __name__ == "__main__":
tic_tac_toe()
# Shivansh Mudgal
# 2202301530052
Objective:- Write a Program in Python to Remove Stop Words for a Given Passage from a Text File.
Step 3 − Remove stop words from the list of words using NLTK.
IMPLEMENTATION
import nltk
nltk.download('stopwords')
stop_words = set(stopwords.words('english'))
text = file.read()
words = text.split()
file.write(' '.join(filtered_words))
# Example usage
input_file = 'input.txt' # Replace with the path to your input text file
remove_stop_words(input_file, output_file)
# 2202301530052
IMPLEMENTATION
import string
def remove_punctuation(paragraph):
return paragraph.translate(translator)
def main():
cleaned_paragraph = remove_punctuation(paragraph)
print(cleaned_paragraph)
if __name__ == "__main__":
main()
# Shivansh Mudgal
# 2202301530052
Objective:- Write a Program in Python to Reverse the String & Reverse the Word of String.
REVERSE A STRING
ALGORITHM
Step 1 − Take the input string.
IMPLEMENTATION
def reverse_string(s):
return s[::-1]
def main():
reversed_string = reverse_string(string)
print("\nReversed String:")
print(reversed_string)
if __name__ == "__main__":
main()
# Shivansh Mudgal
# 2202301530052
IMPLEMENTATION
def reverse_words(sentence):
words = sentence.split()
return reversed_words
def main():
result = reverse_words(sentence)
print(result)
if __name__ == "__main__":
# Shivansh Mudgal
# 2202301530052
Step 2 − Apply the allowed operations (fill, empty, pour) to explore new states.
Step 5 − Stop when we reach the goal (either one of the jugs contains exactly z liters).
IMPLEMENTATION
from collections import defaultdict
print(f"({amt1}, {amt2})")
return True
print(f"({amt1}, {amt2})")
return (
return False
print("Steps:")
# Shivansh Mudgal
# 2202301530052
Objective:- Write a Program in Python to POS (Parts of Speech) Tagging for the Given Sentence using
NLTK.
Step 2 − Use the nltk.pos_tag() function to assign parts of speech to each word.
IMPLEMENTATION
Import nltk
nltk.download('punkt', quiet=True)
nltk.download('averaged_perceptron_tagger', quiet=True)
def pos_tagging(sentence):
"""
"""
return tagged_words
def main():
"""
Main function to get input sentence from user and perform POS tagging.
"""
if __name__ == "__main__":
main()
# Shivansh Mudgal
# 2202301530052