0% found this document useful (0 votes)
25 views28 pages

Shivansh Ai

ai file
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views28 pages

Shivansh Ai

ai file
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

INDEX

Sr. No Experiment Date Signature

1. Write a Program to Implement Recursion of Linear Search &


Binary Search using Python.

2. Write a Program to Implement Breadth First Search using


Python.

3. Write a Program to Implement Depth First Search using


Python.

4. Write a Program in Python for Sorting the Data using Apply


Insertion sort.

5. Write a Program in Python to Sort the Sentence in


Alphabetical Order.

6. Write a Program in Python to Implement Tic Tac Toe Game.

7. Write a Program in Python to Remove Stop Words for a Given


Passage from a Text File.

8. Write a Program in Python to Remove Punctuation from the


Paragraph.

9. Write a Program in Python to Reverse the String & Reverse


the Word of String.

10. Write a Program in Python to Implement Water Jug Problem.

11. Write a Program in Python to POS (Parts of Speech) Tagging


for the Given Sentence using NLTK.

1 2202301530052| Shivansh Mudgal


Experiment No. 1

Objective:- Write a Program to Implement Recursion of Linear Search & Binary Search using Python.

LINEAR SEARCH ALGORITHM


Step 1 − Start from the 0th index of the input array, compare the key value with the value present in the 0th
index.

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):

if index >= len(arr):

return -1

if arr[index] == target:

return index

return linear_search_recursive(arr, target, index + 1)

try:

arr = list(map(int, input("Enter an array (space-separated): ").split()))

target = int(input("Enter the target value: "))

result = linear_search_recursive(arr, target)

if result != -1:

else:

print("Target not found in the array.")

except ValueError:

print("Please enter valid integers for the array and target.")

# Shivansh Mudgal

# 2202301530052

2 2202301530052| Shivansh Mudgal


BINARY SEARCH ALGORITHM
Step 1 − Find the middle element of the array.

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):

if low > high:

return -1

mid = (low + high) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

return binary_search_recursive(arr, target, mid + 1, high)

else:

return binary_search_recursive(arr, target, low, mid - 1)

try:

arr = list(map(int, input("Enter a sorted array (space-separated): ").split()))

target = int(input("Enter the target value: "))

result = binary_search_recursive(arr, target, 0, len(arr) - 1)

if result != -1:

3 2202301530052| Shivansh Mudgal


print(f"Target found at index {result}.")

else:

print("Target not found in the array.")

except ValueError:

print("Please enter valid integers for the array and target.")

# Shivansh Mudgal

# 2202301530052

4 2202301530052| Shivansh Mudgal


Experiment No. 2

Objective:- Write a Program to Implement Breadth First Search using Python.

BREADTH FIRST SEARCH ALGORITHM


Step 1 − Initialize a queue and add the root node to the queue.

Step 2 − While the queue is not empty:

Remove the front node from the queue and process it.

Add all its unvisited neighboring nodes to the queue.


Step 3 − Repeat the above steps until all nodes are visited.

IMPLEMENTATION
graph = {

'A': ['B', 'C'],

'B': ['D', 'E'],

'C': ['F'],

'D': [],

'E': ['F'],

'F': []

visited = []

queue = []

def bfs(visited, graph, node):

visited.append(node)

queue.append(node)

while queue:

s = queue.pop(0)

print(s, end=" ")

for neighbour in graph[s]:

if neighbour not in visited:

visited.append(neighbour)

queue.append(neighbour)

bfs(visited, graph, 'A')

5 2202301530052| Shivansh Mudgal


# Shivansh Mudgal

# 2202301530052

6 2202301530052| Shivansh Mudgal


Experiment No. 3

Objective:- Write a Program to Implement Depth First Search using Python.

DEPTH FIRST SEARCH ALGORITHM


Step 1 − Start at the root node and mark it as visited.

Step 2 − Visit all the unvisited neighbours of the current node.

Step 3 − Repeat the process for every unvisited node until all nodes are visited.

Step 4 − DFS can be implemented using recursion or using a stack

IMPLEMENTATION
graph = {

'A': ['B', 'C'],

'B': ['D', 'E'],

'C': ['F'],

'D': [],

'E': ['F'],

'F': []

visited = set()

def dfs(visited, graph, node):

if node not in visited:

print(node)

visited.add(node)

for neighbour in graph[node]:

dfs(visited, graph, neighbour)

dfs(visited, graph, 'A')

# Shivansh Mudgal

# 2202301530052

7 2202301530052| Shivansh Mudgal


8 2202301530052| Shivansh Mudgal
Experiment No. 4

Objective:- Write a Program in Python for Sorting the Data using Apply Insertion sort.

INSERTION SORT ALGORITHM


Step 1 − Start with the second element (index 1) because the first element is already "sorted" by
itself.
Step 2 − Compare the current element with the elements in the sorted portion of the array (to its
left).
Step 3 − Shift all elements greater than the current element to the right.

Step 4 − Insert the current element into its correct position.

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):

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

if __name__ == "__main__":

try:

arr = list(map(int, input("Enter the numbers to sort (space-separated): ").split()))

print("Original array:", arr)

insertion_sort(arr)

print("Sorted array:", arr)

except ValueError:

print("Please enter a valid list of integers.")

# Shivansh Mudgal

# 2202301530052

9 2202301530052| Shivansh Mudgal


10 2202301530052| Shivansh Mudgal
Experiment No. 5

Objective:- Write a Program in Python to Sort the Sentence in Alphabetical Order.

SENTENCE IN ALPHABETICAL ORDER


ALGORITHM
Step 1 − Split the sentence into a list of words.

Step 2 − Sort the list of words alphabetically.

Step 3 − Join the sorted list of words back into a sentence.

Step 4 − Print or return the sorted sentence

IMPLEMENTATION

def sort_sentence(sentence):

words = sentence.split()

words.sort(key=str.lower)

sorted_sentence = ' '.join(words)

return sorted_sentence

if __name__ == "__main__":

sentence = input("Enter a sentence: ")

sorted_sentence = sort_sentence(sentence)

print("Sorted sentence:", sorted_sentence)

# Shivansh Mudgal

# 2202301530052

11 2202301530052| Shivansh Mudgal


Experiment No. 6

Objective:- Write a Program in Python to Implement Tic Tac Toe Game.

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):

for row in board:

print(" | ".join(row))

print("-" * 9)

def check_winner(board):

# Check rows and columns

for i in range(3):

if board[i][0] == board[i][1] == board[i][2] != " ":

return board[i][0]

if board[0][i] == board[1][i] == board[2][i] != " ":

return board[0][i]

# Check diagonals

if board[0][0] == board[1][1] == board[2][2] != " ":

return board[0][0]

if board[0][2] == board[1][1] == board[2][0] != " ":

return board[0][2]

# Check for a tie

if all(board[i][j] != " " for i in range(3) for j in range(3)):

return "Tie"

return None

def minimax(board, depth, is_maximizing):

12 2202301530052| Shivansh Mudgal


winner = check_winner(board)

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):

if board[i][j] == " ":

board[i][j] = "O"

score = minimax(board, depth + 1, False)

board[i][j] = " "

best_score = max(best_score, score)

return best_score

else:

best_score = math.inf

for i in range(3):

for j in range(3):

if board[i][j] == " ":

board[i][j] = "X"

score = minimax(board, depth + 1, True)

board[i][j] = " "

best_score = min(best_score, score)

return best_score

def best_move(board):

move = None

for i in range(3):

for j in range(3):

13 2202301530052| Shivansh Mudgal


if board[i][j] == " ":

board[i][j] = "O"

score = minimax(board, 0, False)

board[i][j] = " "

if score > best_score:

best_score = score

move = (i, j)

return move

def tic_tac_toe():

board = [[" " for _ in range(3)] for _ in range(3)]

print("Tic-Tac-Toe!")

print("You are X and the computer is O.")

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, col = map(int, user_move.split())

row -= 1

col -= 1

if board[row][col] == " ":

board[row][col] = "X"

break

else:

print("Cell is already occupied. Try again.")

except (ValueError, IndexError):

print("Invalid input. Please enter row and column as two numbers (e.g., 1 1).")

print_board(board)

result = check_winner(board)

if result:

14 2202301530052| Shivansh Mudgal


if result == "X":

print("You win!")

elif result == "O":

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!")

elif result == "O":

print("Computer wins!")

else:

print("It's a tie!")

break

if __name__ == "__main__":

tic_tac_toe()

# Shivansh Mudgal

# 2202301530052

15 2202301530052| Shivansh Mudgal


16 2202301530052| Shivansh Mudgal
17 2202301530052| Shivansh Mudgal
Experiment No. 7

Objective:- Write a Program in Python to Remove Stop Words for a Given Passage from a Text File.

REMOVE STOP WORDS FROM A PASSAGE USING NLTK


ALGORITHM
Step 1 − Load the passage from a text file.

Step 2 − Tokenize the passage into words.

Step 3 − Remove stop words from the list of words using NLTK.

Step 4 − Print the cleaned passage without the stop words.

IMPLEMENTATION
import nltk

from nltk.corpus import stopwords

# Download stopwords from nltk if not already present

nltk.download('stopwords')

def remove_stop_words(input_file, output_file):

# Load the list of stop words

stop_words = set(stopwords.words('english'))

# Read the input file

with open(input_file, 'r') as file:

text = file.read()

# Tokenize the text into words

words = text.split()

# Remove stop words

filtered_words = [word for word in words if word.lower() not in stop_words]

# Write the filtered text to the output file

with open(output_file, 'w') as file:

file.write(' '.join(filtered_words))

print(f"Stop words removed and output saved to {output_file}")

# Example usage

input_file = 'input.txt' # Replace with the path to your input text file

output_file = 'output.txt' # Replace with the desired output file path

remove_stop_words(input_file, output_file)

18 2202301530052| Shivansh Mudgal


# Shivansh Mudgal

# 2202301530052

19 2202301530052| Shivansh Mudgal


Experiment No. 8

Objective:- Write a Program in Python to Remove Punctuation from the Paragraph.

REMOVE PUNCTUATION FROM A GIVEN STRING


ALGORITHM
Step 1 − Define the input string.

Step 2 − Iterate through each character in the string.

Step 3 − Check if the character is not a punctuation mark.

Step 4 − Append non-punctuation characters to a new string.

Step 5 − Print the cleaned string without punctuation.

IMPLEMENTATION
import string

def remove_punctuation(paragraph):

translator = str.maketrans("", "", string.punctuation)

return paragraph.translate(translator)

def main():

paragraph = input("Enter a paragraph:\n")

cleaned_paragraph = remove_punctuation(paragraph)

print("\nParagraph without punctuation:\n")

print(cleaned_paragraph)

if __name__ == "__main__":

main()

# Shivansh Mudgal

# 2202301530052

20 2202301530052| Shivansh Mudgal


21 2202301530052| Shivansh Mudgal
Experiment No. 9

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.

Step 2 − Use slicing or a loop to reverse the string.

Step 3 − Print the reversed string.

IMPLEMENTATION
def reverse_string(s):

return s[::-1]

def main():

string = input("Enter a string to reverse: ")

reversed_string = reverse_string(string)

print("\nReversed String:")

print(reversed_string)

if __name__ == "__main__":

main()

# Shivansh Mudgal

# 2202301530052

22 2202301530052| Shivansh Mudgal


REVERSE WORDS IN A STRING
ALGORITHM
Step 1 − Take the input string.

Step 2 − Split the string into words.

Step 3 − Reverse the order of the words.

Step 4 − Join the reversed words back into a single string.

Step 5 − Print the resulting string with reversed words.

IMPLEMENTATION
def reverse_words(sentence):

words = sentence.split()

reversed_words = ' '.join(word[::-1] for word in words)

return reversed_words

def main():

sentence = input("Enter a sentence to reverse the words: ")

result = reverse_words(sentence)

print("\nReversed Words in String:")

print(result)

if __name__ == "__main__":

23 2202301530052| Shivansh Mudgal


main()

# Shivansh Mudgal

# 2202301530052

24 2202301530052| Shivansh Mudgal


Experiment No. 10

Objective:- Write a Program in Python to Implement Water Jug Problem.

WATER JUG PROBLEM


ALGORITHM
Step 1 − Start with both jugs empty.

Step 2 − Apply the allowed operations (fill, empty, pour) to explore new states.

Step 3 − Use a queue to explore states level by level (BFS).

Step 4 − Track visited states to avoid infinite loops.

Step 5 − Stop when we reach the goal (either one of the jugs contains exactly z liters).

IMPLEMENTATION
from collections import defaultdict

jug1, jug2, aim = 4, 3, 2

visited = defaultdict(lambda: False)

def waterJugSolver(amt1, amt2):

if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):

print(f"({amt1}, {amt2})")

return True

if not visited[(amt1, amt2)]:

print(f"({amt1}, {amt2})")

visited[(amt1, amt2)] = True

return (

waterJugSolver(0, amt2) or # Empty jug1

waterJugSolver(amt1, 0) or # Empty jug2

waterJugSolver(jug1, amt2) or # Fill jug1

waterJugSolver(amt1, jug2) or # Fill jug2

waterJugSolver( # Pour water from jug2 to jug1

amt1 + min(amt2, (jug1 - amt1)),

amt2 - min(amt2, (jug1 - amt1)) ) or

waterJugSolver( # Pour water from jug1 to jug2

amt1 - min(amt1, (jug2 - amt2)),

amt2 + min(amt1, (jug2 - amt2)) ))

25 2202301530052| Shivansh Mudgal


else:

return False

print("Steps:")

if not waterJugSolver(0, 0):

print("No solution found.")

# Shivansh Mudgal

# 2202301530052

26 2202301530052| Shivansh Mudgal


Experiment No. 11

Objective:- Write a Program in Python to POS (Parts of Speech) Tagging for the Given Sentence using
NLTK.

POS (PARTS OF SPEECH) TAGGING USING NLTK


ALGORITHM
Step 1 − Tokenize the input sentence into words.

Step 2 − Use the nltk.pos_tag() function to assign parts of speech to each word.

Step 3 − Display the tagged words.

IMPLEMENTATION
Import nltk

from nltk.tokenize import word_tokenize

from nltk import pos_tag

# Ensure required NLTK resources are downloaded

nltk.download('punkt', quiet=True)

nltk.download('averaged_perceptron_tagger', quiet=True)

def pos_tagging(sentence):

"""

Tokenizes the input sentence and performs POS tagging.

:param sentence: A string containing the sentence to tag.

:return: List of tuples with words and their POS tags.

"""

tokens = word_tokenize(sentence) # Tokenizing the sentence

tagged_words = pos_tag(tokens) # Applying POS tagging

return tagged_words

def main():

"""

Main function to get input sentence from user and perform POS tagging.

"""

sentence = input("Enter a sentence for POS tagging: ") # User input

result = pos_tagging(sentence) # Perform POS tagging

print("\nParts of Speech (POS) Tagging:")

27 2202301530052| Shivansh Mudgal


for word, pos in result: # Display each word with its POS tag

print(f"{word} -> {pos}")

if __name__ == "__main__":

main()

# Shivansh Mudgal

# 2202301530052

28 2202301530052| Shivansh Mudgal

You might also like