MCS Artificial Intelligence Practical Programs

MCS Artificial Intelligence Practical Programs


Slip1:

Q.1) Python program that demonstrates the hill climbing algorithm to find the maximum of a mathematical function.(For example f(x) = -x^2 + 4x)


# -*- coding: utf-8 -*-
"""
Created on Mon Dec 11 20:14:33 2023

@author: learnwithnil
"""

def objective_function(x):
    return -x**2 + 4*x

def hill_climbing(max_iterations=1000, step_size=0.01):
    current_x = 0.0  # Starting point
    current_value = objective_function(current_x)

    for _ in range(max_iterations):
        next_x = current_x + step_size
        next_value = objective_function(next_x)

        if next_value > current_value:
            current_x = next_x
            current_value = next_value
        else:
            break

    return current_x, current_value

if __name__ == "__main__":
    result_x, result_value = hill_climbing()

    print(f"Optimal x: {result_x}")
    print(f"Maximum value: {result_value}")

Optimal x: 2.0000000000000013

Maximum value: 4.0


Q.2) Write a Python program to implement Depth First Search algorithm. Refer the following graph as an Input for the program. [Initial node=1,Goal node=8]


import sys
def dfs(graph, start,goal,visited=None):
    if visited is None:
        visited = set()

    visited.add(start)
    print("Visited node:", start)
    if start==goal:
        sys.exit()
       
    for neighbor in graph[start]:
       
       
        if neighbor not in visited:
            dfs(graph, neighbor,goal,visited)
       

# Example graph represented as an adjacency list
graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [8],
    5: [8],
    6: [8],
    7: [8],
    8: []
}

# Specify the initial node
start_node = 1
goal_node =8
print("Depth First Search starting from node", start_node)
dfs(graph,start_node,goal_node)

Depth First Search starting from node 1

Visited node: 1

Visited node: 2

Visited node: 4

Visited node: 8


OR

graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6,7],
    4: [8],
    5: [8],
    6: [7],
    7: [8],
    8: []
}

def dfs(graph, start, goal, visited=None):
    if visited is None:
        visited = set()

    visited.add(start)

    if start == goal:
        print("Goal node found!")
        return True

    for neighbor in graph[start]:
        if neighbor not in visited:
            if dfs(graph, neighbor, goal, visited):
                return True

    return False

if __name__ == "__main__":
    start_node = 1
    goal_node = 8

    if dfs(graph, start_node, goal_node):
        print(f"Path from {start_node} to {goal_node} exists.")
    else:
        print(f"Path from {start_node} to {goal_node} does not exist.")


Goal node found!

Path from 1 to 8 exists.


def dfs(graph, start, goal, visited=None):
    if visited is None:
        visited = set()

    visited.add(start)

    if start == goal:
        return [start]

    for neighbor in graph.get(start, []):
        if neighbor not in visited:
            path = dfs(graph, neighbor, goal, visited)
            if path:
                return [start] + path

    return None

# Example graph represented as an adjacency list
graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [8],
    5: [],
    6: [],
    7: [],
    8: []
}

# Specify the initial and goal nodes
initial_node = 1
goal_node = 8

# Run DFS and print the result
result = dfs(graph, initial_node, goal_node)

if result:
    print(f"DFS path from {initial_node} to {goal_node}: {result}")
else:
    print(f"No path found from {initial_node} to {goal_node}")

Slip 2:


Write a python program to generate Calendar for the given month and year?


import calendar

def generate_calendar(year, month):
    cal = calendar.monthcalendar(year, month)
    month_name = calendar.month_name[month]

    print(f"Calendar for {month_name} {year}:")
    print(" Mo Tu We Th Fr Sa Su")

    for week in cal:
        for day in week:
            if day == 0:
                print("   ", end=" ")
            else:
                print(f"{day:2} ", end=" ")

        print()

if __name__ == "__main__":
    year = int(input("Enter the year: "))
    month = int(input("Enter the month (1-12): "))

    generate_calendar(year, month)


Enter the year: 2023


Enter the month (1-12): 12

Calendar for December 2023:

 Mo  Tu We Th Fr Sa Su

                          1   2   3  

 4    5    6    7    8    9  10  

11  12  13  14  15  16  17  

18  19  20  21  22  23  24  

25  26  27  28  29  30  31  


2)Write a Python program to implement Depth First Search algorithm. Refer the following graph as an Input for the program.[Initial node=1,Goal node=7].


import sys
def dfs(graph, start,goal,visited=None):
    if visited is None:
        visited = set()

    visited.add(start)
    print("Visited node:", start)
    if start==goal:
        sys.exit()
       
    for neighbor in graph[start]:
       
       
        if neighbor not in visited:
            dfs(graph, neighbor,goal,visited)
       

# Example graph represented as an adjacency list
graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [8],
    5: [8],
    6: [8],
    7: [8],
    8: []
}

# Specify the initial node
start_node = 1
goal_node =8
print("Depth First Search starting from node", start_node)
dfs(graph,start_node,goal_node)

Depth First Search starting from node 1

Visited node: 1

Visited node: 2

Visited node: 4

Visited node: 8



OR

def dfs(graph, start, goal, visited=None):
    if visited is None:
        visited = set()

    visited.add(start)

    if start == goal:
        return [start]

    for neighbor in graph.get(start, []):
        if neighbor not in visited:
            path = dfs(graph, neighbor, goal, visited)
            if path:
                return [start] + path

    return None

# Example graph represented as an adjacency list
graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [8],
    5: [],
    6: [],
    7: [],
    8: []
}

# Specify the initial and goal nodes
initial_node = 1
goal_node = 8

# Run DFS and print the result
result = dfs(graph, initial_node, goal_node)

if result:
    print(f"DFS path from {initial_node} to {goal_node}: {result}")
else:
    print(f"No path found from {initial_node} to {goal_node}")

OR


graph = {
    1: [2, 3],
    2: [4],
    3: [2],
    4: [5,6],
    5: [3,7],
    6: [7],
    7: [6],
    8: []
}

def dfs(graph, start, goal, visited=None):
    if visited is None:
        visited = set()

    visited.add(start)

    if start == goal:
        print("Goal node found!")
        return True

    for neighbor in graph[start]:
        if neighbor not in visited:
            if dfs(graph, neighbor, goal, visited):
                return True

    return False

if __name__ == "__main__":
    start_node = 1
    goal_node = 8

    if dfs(graph, start_node, goal_node):
        print(f"Path from {start_node} to {goal_node} exists.")
    else:
        print(f"Path from {start_node} to {goal_node} does not exist.")




Slip 3:


Q.1) Write a python program to remove punctuations from the given string? .[ 10 marks ] 

import string

def remove_punctuation(input_string):
    # Get the set of punctuation characters
    punctuations = set(string.punctuation)

    # Remove punctuations from the input string
    result_string = ''.join(char for char in input_string if char not in punctuations)

    return result_string

if __name__ == "__main__":
    input_string = input("Enter a string with punctuations: ")

    result = remove_punctuation(input_string)

    print("String without punctuations:", result)

Enter a string with punctuations: Swapnil!learn,with,nil

String without punctuations: Swapnillearnwithnil



Write a Python program to implement Depth First Search algorithm. Refer the following graph as an Input for the program.[Initial node=2,Goal node=7] 


import sys
def dfs(graph, start,goal,visited=None):
    if visited is None:
        visited = set()

    visited.add(start)
    print("Visited node:", start)
    if start==goal:
        sys.exit()
       
    for neighbor in graph[start]:
       
       
        if neighbor not in visited:
            dfs(graph, neighbor,goal,visited)
       

# Example graph represented as an adjacency list
graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [8],
    5: [8],
    6: [8],
    7: [8],
    8: []
}

# Specify the initial node
start_node = 1
goal_node =8
print("Depth First Search starting from node", start_node)
dfs(graph,start_node,goal_node)

Depth First Search starting from node 1

Visited node: 1

Visited node: 2

Visited node: 4

Visited node: 8


Slip 4:


Q.1)Write a program to implement Hangman game using python. [10 Marks] Description: Hangman is a classic word-guessing game. The user should guess the word correctly by entering alphabets of the user choice. The Program will get input as single alphabet from the user and it will matchmaking with the alphabets in the original 


import random

def hangman():
    secret_word = random.choice(["python", "hangman", "programming", "computer", "science", "algorithm"])
    guessed_letters, attempts = set(), 6
   
    while attempts > 0 and set(secret_word) > guessed_letters:
        print("Current word:", ''.join(letter if letter in guessed_letters else '_' for letter in secret_word))
        guess = input("Guess a letter: ").lower()
        guessed_letters.add(guess)
        attempts -= guess not in secret_word

    print(f"{'Congratulations!' if set(secret_word) <= guessed_letters else 'Sorry, you ran out of attempts. The word was: ' + secret_word}")

if __name__ == "__main__":
    hangman()

OR

import random

def choose_word():
    words = ["python", "hangman", "programming", "computer", "nil", "algorithm", "shreya"]
    return random.choice(words)

def display_word(word, guessed_letters):
    display = ""
    for letter in word:
        if letter in guessed_letters:
            display += letter
        else:
            display += "_"
    return display

def hangman():
    print("Welcome to Hangman!")
    secret_word = choose_word()
    guessed_letters = []
    attempts_left = 6

    while attempts_left > 0:
        print("\nCurrent Word:", display_word(secret_word, guessed_letters))
        guess = input("Enter a letter: ").lower()

        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a single alphabet.")
            continue

        if guess in guessed_letters:
            print("You've already guessed that letter. Try again.")
            continue

        guessed_letters.append(guess)

        if guess not in secret_word:
            attempts_left -= 1
            print(f"Incorrect! Attempts left: {attempts_left}")
        else:
            print("Correct guess!")

        if all(letter in guessed_letters for letter in secret_word):
            print("\nCongratulations! You guessed the word:", secret_word)
            break

    if attempts_left == 0:
        print("\nOut of attempts! The word was:", secret_word)

if __name__ == "__main__":
    hangman()

Welcome to Hangman!


Current Word: ______


Enter a letter: n

Correct guess!


Current Word: _____n


Enter a letter: h

Correct guess!


Current Word: ___h_n


Enter a letter: e

Incorrect! Attempts left: 5


Current Word: ___h_n


Enter a letter: a

Incorrect! Attempts left: 4


Current Word: ___h_n


Enter a letter: n

You've already guessed that letter. Try again.


Current Word: ___h_n


Enter a letter: u

Incorrect! Attempts left: 3


Current Word: ___h_n


Enter a letter: m

Incorrect! Attempts left: 2


Current Word: ___h_n


Enter a letter: n

You've already guessed that letter. Try again.


Current Word: ___h_n


Enter a letter: p

Correct guess!


Current Word: p__h_n


Enter a letter: y

Correct guess!


Current Word: py_h_n


Enter a letter: th

Please enter a single alphabet.


Current Word: py_h_n


Enter a letter: t

Correct guess!


Current Word: pyth_n


Enter a letter: o

Correct guess!


Congratulations! You guessed the word: python




2]Write a Python program to implement Breadth First Search algorithm. Refer the following graph as an Input for the program.[Initial node=1,Goal node=8] 

BFS:

def bfs(graph, start, goal):
    visited = set()
    queue = [(start, [start])]

    while queue:
        current_node, path = queue.pop(0)

        if current_node == goal:
            return path

        if current_node not in visited:
            visited.add(current_node)

            for neighbor in graph[current_node]:
                if neighbor not in visited:
                    queue.append((neighbor, path + [neighbor]))

    return None

# Example graph represented as an adjacency list
graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [8],
    5: [],
    6: [],
    7: [],
    8: []
}

# Specify the initial and goal nodes
initial_node = 1
goal_node = 8

# Run BFS and print the result
result = bfs(graph, initial_node, goal_node)

if result:
    print(f"BFS path from {initial_node} to {goal_node}: {result}")
else:
    print(f"No path found from {initial_node} to {goal_node}")


Slip 5:


Q.1) Write a python program to implement Lemmatization using NLTK


import nltk
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize

nltk.download('punkt')
nltk.download('wordnet')

def lemmatize_text(text):
    lemmatizer = WordNetLemmatizer()
    tokens = word_tokenize(text)
    lemmatized_tokens = [lemmatizer.lemmatize(token) for token in tokens]
    lemmatized_text = ' '.join(lemmatized_tokens)
    return lemmatized_text

if __name__ == "__main__":
    input_text = input("Enter a sentence for lemmatization: ")

    lemmatized_result = lemmatize_text(input_text)

    print("\nOriginal Text:", input_text)
    print("Lemmatized Text:", lemmatized_result)


Enter a sentence for lemmatization: The quick brown foxes are jumping over the lazy dogs.


Original Text: The quick brown foxes are jumping over the lazy dogs.

Lemmatized Text: The quick brown fox are jumping over the lazy dog .



Q.2) Write a Python program to implement Breadth First Search algorithm. Refer the following graph as an Input for the program.[Initial node=1,Goal node=8]


 BFS:

def bfs(graph, start, goal):
    visited = set()
    queue = [(start, [start])]

    while queue:
        current_node, path = queue.pop(0)

        if current_node == goal:
            return path

        if current_node not in visited:
            visited.add(current_node)

            for neighbor in graph[current_node]:
                if neighbor not in visited:
                    queue.append((neighbor, path + [neighbor]))

    return None

# Example graph represented as an adjacency list
graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [8],
    5: [],
    6: [],
    7: [],
    8: []
}

# Specify the initial and goal nodes
initial_node = 1
goal_node = 8

# Run BFS and print the result
result = bfs(graph, initial_node, goal_node)

if result:
    print(f"BFS path from {initial_node} to {goal_node}: {result}")
else:
    print(f"No path found from {initial_node} to {goal_node}")




Slip 6:

Write a python program to remove stop words for a given passage from a text file using NLTK?.

import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

nltk.download('stopwords')
nltk.download('punkt')

def remove_stop_words(text):
    stop_words = set(stopwords.words('english'))
    words = word_tokenize(text)
    filtered_words = [word for word in words if word.lower() not in stop_words]
    return ' '.join(filtered_words)

def read_text_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

if __name__ == "__main__":
    file_path = input("Enter the path to the text file: ")

    try:
        passage = read_text_from_file(file_path)
        cleaned_passage = remove_stop_words(passage)

        print("\nOriginal Passage:")
        print(passage)

        print("\nPassage after Removing Stop Words:")
        print(cleaned_passage)
    except FileNotFoundError:
        print("File not found. Please check the file path.")


Enter the path to the text file: Myfile.txt


Original Passage:

# -*- coding: utf-8 -*-

"""

Created on Mon Dec 11 20:56:17 2023


@author: swapnil

"""


My Stop is near by sky

And i'm the Stop of the world...


Passage after Removing Stop Words:

# - * - coding : utf-8 - * - '' '' '' Created Mon Dec 11 20:56:17 2023 @ author : swapnil '' '' '' Stop near sky 'm Stop world ...




Q.2) Write a Python program to implement Breadth First Search algorithm. Refer the following graph as an Input for the program.[Initial node=1,Goal node=8]



BFS:

def bfs(graph, start, goal):
    visited = set()
    queue = [(start, [start])]

    while queue:
        current_node, path = queue.pop(0)

        if current_node == goal:
            return path

        if current_node not in visited:
            visited.add(current_node)

            for neighbor in graph[current_node]:
                if neighbor not in visited:
                    queue.append((neighbor, path + [neighbor]))

    return None

# Example graph represented as an adjacency list
graph = {
    1: [2, 3],
    2: [4, 5],
    3: [6, 7],
    4: [8],
    5: [],
    6: [],
    7: [],
    8: []
}

# Specify the initial and goal nodes
initial_node = 1
goal_node = 8

# Run BFS and print the result
result = bfs(graph, initial_node, goal_node)

if result:
    print(f"BFS path from {initial_node} to {goal_node}: {result}")
else:
    print(f"No path found from {initial_node} to {goal_node}")



slip 7:


Write a python program implement tic-tac-toe using alpha beeta pruning


import math

def print_board(board):
    for row in board:
        print(" ".join(row))
    print()

def is_winner(board, player):
    for row in board:
        if all(cell == player for cell in row):
            return True

    for col in range(3):
        if all(board[row][col] == player for row in range(3)):
            return True

    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
        return True

    return False

def is_full(board):
    return all(cell != ' ' for row in board for cell in row)

def get_winner(board):
    if is_winner(board, 'X'):
        return 'X'
    elif is_winner(board, 'O'):
        return 'O'
    else:
        return None

def evaluate(board):
    winner = get_winner(board)
    if winner == 'X':
        return 1
    elif winner == 'O':
        return -1
    elif is_full(board):
        return 0
    else:
        return None

def minimax(board, depth, alpha, beta, maximizing_player):
    score = evaluate(board)

    if score is not None:
        return score

    if maximizing_player:
        max_eval = -math.inf
        for i in range(3):
            for j in range(3):
                if board[i][j] == ' ':
                    board[i][j] = 'X'
                    eval = minimax(board, depth + 1, alpha, beta, False)
                    board[i][j] = ' '
                    max_eval = max(max_eval, eval)
                    alpha = max(alpha, eval)
                    if beta <= alpha:
                        break
        return max_eval
    else:
        min_eval = math.inf
        for i in range(3):
            for j in range(3):
                if board[i][j] == ' ':
                    board[i][j] = 'O'
                    eval = minimax(board, depth + 1, alpha, beta, True)
                    board[i][j] = ' '
                    min_eval = min(min_eval, eval)
                    beta = min(beta, eval)
                    if beta <= alpha:
                        break
        return min_eval

def find_best_move(board):
    best_val = -math.inf
    best_move = (-1, -1)

    for i in range(3):
        for j in range(3):
            if board[i][j] == ' ':
                board[i][j] = 'X'
                move_val = minimax(board, 0, -math.inf, math.inf, False)
                board[i][j] = ' '

                if move_val > best_val:
                    best_move = (i, j)
                    best_val = move_val

    return best_move

def main():
    board = [[' ' for _ in range(3)] for _ in range(3)]
    current_player = 'X'

    while True:
        print_board(board)

        if current_player == 'X':
            move = find_best_move(board)
            print("Computer plays X at position:", move)
        else:
            move = tuple(map(int, input("Enter your move (row column): ").split()))

        if board[move[0]][move[1]] == ' ':
            board[move[0]][move[1]] = current_player
            winner = get_winner(board)
            if winner:
                print_board(board)
                print(f"{winner} wins!")
                break
            elif is_full(board):
                print_board(board)
                print("It's a tie!")
                break
            else:
                current_player = 'O' if current_player == 'X' else 'X'
        else:
            print("Invalid move. Try again.")

if __name__ == "__main__":
    main()



Computer plays X at position: (0, 0)

X    

     

     



Enter your move (row column): 1 1

X    

  O  

     


Computer plays X at position: (0, 1)

X X  

  O  

     



Enter your move (row column): 0 2

X X O

  O  

     


Computer plays X at position: (2, 0)

X X O

  O  

X    



Enter your move (row column): 1 0

X X O

O O  

X    


Computer plays X at position: (1, 2)

X X O

O O X

X    



Enter your move (row column): 2 2

X X O

O O X

X   O


Computer plays X at position: (2, 1)

X X O

O O X

X X O


It's a tie!




Slip 7:

Q.1)Write a python program implement tic-tac-toe using alpha beeta pruning[

import math

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 13)

def is_winner(board, player):
    for row in board:
        if all(cell == player for cell in row):
            return True

    for col in range(3):
        if all(board[row][col] == player for row in range(3)):
            return True

    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
        return True

    return False

def is_board_full(board):
    return all(cell != ' ' for row in board for cell in row)

def evaluate(board):
    if is_winner(board, 'X'):
        return 1
    elif is_winner(board, 'O'):
        return -1
    elif is_board_full(board):
        return 0
    else:
        return None

def minimax(board, depth, maximizing_player, alpha, beta):
    score = evaluate(board)

    if score is not None:
        return score

    if maximizing_player:
        max_eval = -math.inf
        for i in range(3):
            for j in range(3):
                if board[i][j] == ' ':
                    board[i][j] = 'X'
                    eval = minimax(board, depth + 1, False, alpha, beta)
                    board[i][j] = ' '
                    max_eval = max(max_eval, eval)
                    alpha = max(alpha, eval)
                    if beta <= alpha:
                        break
        return max_eval
    else:
        min_eval = math.inf
        for i in range(3):
            for j in range(3):
                if board[i][j] == ' ':
                    board[i][j] = 'O'
                    eval = minimax(board, depth + 1, True, alpha, beta)
                    board[i][j] = ' '
                    min_eval = min(min_eval, eval)
                    beta = min(beta, eval)
                    if beta <= alpha:
                        break
        return min_eval

def find_best_move(board):
    best_val = -math.inf
    best_move = None

    for i in range(3):
        for j in range(3):
            if board[i][j] == ' ':
                board[i][j] = 'X'
                move_val = minimax(board, 0, False, -math.inf, math.inf)
                board[i][j] = ' '

                if move_val > best_val:
                    best_move = (i, j)
                    best_val = move_val

    return best_move

def play_tic_tac_toe():
    board = [[' ' for _ in range(3)] for _ in range(3)]
    print_board(board)

    while True:
        # Player's move
        row, col = map(int, input("Enter your move (row col): ").split())
        if board[row][col] != ' ':
            print("Invalid move. Cell already occupied. Try again.")
            continue
        board[row][col] = 'O'
        print_board(board)

        # Check if player wins
        if is_winner(board, 'O'):
            print("Congratulations! You win!")
            break

        # Check if the board is full
        if is_board_full(board):
            print("It's a tie!")
            break

        # AI's move
        print("AI is making a move...")
        ai_row, ai_col = find_best_move(board)
        board[ai_row][ai_col] = 'X'
        print_board(board)

        # Check if AI wins
        if is_winner(board, 'X'):
            print("AI wins! Better luck next time.")
            break

        # Check if the board is full
        if is_board_full(board):
            print("It's a tie!")
            break

if __name__ == "__main__":
    play_tic_tac_toe()




Write a Python program to implement Simple Chatbot.


import random

def simple_chatbot():
    print("Hello! I'm a Simple Chatbot. You can type 'bye' to exit.")

    while True:
        user_input = input("You: ").lower()

        if user_input == 'bye':
            print("Chatbot: Goodbye! Have a great day.")
            break
        elif 'how are you' in user_input:
            print("Chatbot: I'm doing well, thank you!")
        elif 'your name' in user_input:
            print("Chatbot: I'm just a simple chatbot.")
        elif 'joke' in user_input:
            jokes = [
                "Why did the scarecrow win an award? Because he was outstanding in his field!",
                "What did one wall say to the other wall? I'll meet you at the corner.",
                "Why don't scientists trust atoms? Because they make up everything!"
            ]
            print(f"Chatbot: {random.choice(jokes)}")
        else:
            print("Chatbot: I'm sorry, I didn't understand that.")

if __name__ == "__main__":
    simple_chatbot()



Slip 8:

Q.1) Write a Python program to accept a string. Find and print the number of upper case alphabets and lower case alphabets. 


def count_upper_lower(string):
    upper_count = 0
    lower_count = 0

    for char in string:
        if char.isupper():
            upper_count += 1
        elif char.islower():
            lower_count += 1

    print("Number of uppercase alphabets:", upper_count)
    print("Number of lowercase alphabets:", lower_count)

if __name__ == "__main__":
    user_input = input("Enter a string: ")
    count_upper_lower(user_input)



Write a Python program to solve tic-tac-toe problem


def check_winner(board):
    # Check rows
    for row in board:
        if all(cell == 'X' for cell in row):
            return 'X'
        elif all(cell == 'O' for cell in row):
            return 'O'

    # Check columns
    for col in range(3):
        if all(board[row][col] == 'X' for row in range(3)):
            return 'X'
        elif all(board[row][col] == 'O' for row in range(3)):
            return 'O'

    # Check diagonals
    if all(board[i][i] == 'X' for i in range(3)) or all(board[i][2 - i] == 'X' for i in range(3)):
        return 'X'
    elif all(board[i][i] == 'O' for i in range(3)) or all(board[i][2 - i] == 'O' for i in range(3)):
        return 'O'

    return None

def check_tie(board):
    return all(cell != ' ' for row in board for cell in row)

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def tic_tac_toe():
    board = [[' ' for _ in range(3)] for _ in range(3)]
    player = 'X'

    while True:
        print_board(board)
        row, col = map(int, input(f"Player {player}, enter your move (row col): ").split())

        if board[row][col] == ' ':
            board[row][col] = player
        else:
            print("Invalid move. Cell already occupied. Try again.")
            continue

        winner = check_winner(board)
        if winner:
            print_board(board)
            print(f"Player {winner} wins!")
            break

        if check_tie(board):
            print_board(board)
            print("It's a tie!")
            break

        player = 'O' if player == 'X' else 'X'

if __name__ == "__main__":
    tic_tac_toe()




Slip 9:


Write python program to solve 8 puzzle problem using A* algorithm [


import heapq

class PuzzleNode:
    def __init__(self, state, parent=None, move=None):
        self.state = state
        self.parent = parent
        self.move = move
        self.cost = 0 if parent is None else parent.cost + 1

    def __lt__(self, other):
        return (self.cost + self.heuristic()) < (other.cost + other.heuristic())

    def __eq__(self, other):
        return self.state == other.state

    def __hash__(self):
        return hash(tuple(map(tuple, self.state)))

    def heuristic(self):
        # Manhattan distance heuristic
        goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
        h = 0
        for i in range(3):
            for j in range(3):
                if self.state[i][j] != 0:
                    goal_i, goal_j = divmod(self.state[i][j] - 1, 3)
                    h += abs(i - goal_i) + abs(j - goal_j)
        return h

    def get_possible_moves(self):
        moves = []
        i, j = next((i, j) for i, row in enumerate(self.state) for j, value in enumerate(row) if value == 0)
        for move_i, move_j in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
            new_i, new_j = i + move_i, j + move_j
            if 0 <= new_i < 3 and 0 <= new_j < 3:
                new_state = [row.copy() for row in self.state]
                new_state[i][j], new_state[new_i][new_j] = new_state[new_i][new_j], new_state[i][j]
                moves.append(PuzzleNode(new_state, self, (i, j)))
        return moves

def a_star(initial_state):
    initial_node = PuzzleNode(initial_state)
    if initial_node.heuristic() == 0:
        return [initial_node.state]

    visited = set()
    priority_queue = [initial_node]

    while priority_queue:
        current_node = heapq.heappop(priority_queue)
        visited.add(current_node)

        for neighbor in current_node.get_possible_moves():
            if neighbor not in visited:
                if neighbor.heuristic() == 0:
                    # Found the solution
                    path = [neighbor.state]
                    while neighbor.parent:
                        path.append(neighbor.parent.state)
                        neighbor = neighbor.parent
                    path.reverse()
                    return path
                heapq.heappush(priority_queue, neighbor)

    return None

def print_solution(solution):
    for step, state in enumerate(solution):
        print(f"Step {step + 1}:")
        for row in state:
            print(row)
        print("\n")

if __name__ == "__main__":
    initial_state = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 0, 8]
    ]

    solution = a_star(initial_state)

    if solution:
        print_solution(solution)
    else:
        print("No solution found.")




 Write a Python program to solve water jug problem. 2 jugs with capacity 5 gallon and 7 gallon are given with unlimited water supply respectively. The target to achieve is 4 gallon of water in second jug.


def water_jug_problem(jug1, jug2, target):
    def pour(jug1, jug2):
        # Pour water from jug1 to jug2
        if jug1[0] > 0 and jug2[1] < jug2[2]:
            amount = min(jug1[0], jug2[2] - jug2[1])
            jug1[0] -= amount
            jug2[1] += amount
            yield jug1, jug2

        # Pour water from jug2 to jug1
        if jug2[1] > 0 and jug1[0] < jug1[1]:
            amount = min(jug2[1], jug1[1] - jug1[0])
            jug2[1] -= amount
            jug1[0] += amount
            yield jug1, jug2

    def dfs(current_state, visited):
        if current_state[0][0] == target or current_state[1][0] == target:
            return [current_state[0][0], current_state[1][0]]

        visited.add((current_state[0][0], current_state[1][0]))

        for next_state in pour(*current_state):
            if (next_state[0][0], next_state[1][0]) not in visited:
                result = dfs(next_state, visited)
                if result:
                    return [current_state[0][0], current_state[1][0]] + result

        return None

    initial_state = [[0, 5], [0, 7]]
    final_state = dfs(initial_state, set())

    if final_state:
        print(f"Solution found: {final_state[0]} gallons in the 5-gallon jug and {final_state[1]} gallons in the 7-gallon jug.")
    else:
        print("No solution found.")

if __name__ == "__main__":
    water_jug_problem(5, 7, 4)



Slip 10:


Write Python program to implement crypt arithmetic problem TWO+TWO=FOUR


from itertools import permutations

def is_valid_assignment(assignment):
    t, w, o, f, u, r = assignment
    return 2 * (100 * t + 10 * w + o) == 1000 * f + 100 * o + 10 * u + r

def solve_cryptarithmetic():
    for perm in permutations(range(10), 6):
        assignment = {'T': perm[0], 'W': perm[1], 'O': perm[2], 'F': perm[3], 'U': perm[4], 'R': perm[5]}
        if assignment['T'] == 0 or assignment['F'] == 0:
            continue

        if is_valid_assignment(assignment):
            print("Solution found:")
            print(f"  T W O\n+ T W O\n-------\n  F O U R")
            print(f"  {assignment['T']} {assignment['W']} {assignment['O']}")
            print(f"+ {assignment['T']} {assignment['W']} {assignment['O']}")
            print("-------")
            print(f"  {assignment['F']} {assignment['O']} {assignment['U']} {assignment['R']}")
            return

    print("No solution found.")

if __name__ == "__main__":
    solve_cryptarithmetic()



Write a Python program to implement Simple Chatbot.



import random

def simple_chatbot():
    print("Hello! I'm a Simple Chatbot. You can type 'bye' to exit.")

    while True:
        user_input = input("You: ").lower()

        if user_input == 'bye':
            print("Chatbot: Goodbye! Have a great day.")
            break
        elif 'how are you' in user_input:
            print("Chatbot: I'm doing well, thank you!")
        elif 'your name' in user_input:
            print("Chatbot: I'm just a simple chatbot.")
        elif 'joke' in user_input:
            jokes = [
                "Why did the scarecrow win an award? Because he was outstanding in his field!",
                "What did one wall say to the other wall? I'll meet you at the corner.",
                "Why don't scientists trust atoms? Because they make up everything!"
            ]
            print(f"Chatbot: {random.choice(jokes)}")
        else:
            print("Chatbot: I'm sorry, I didn't understand that.")

if __name__ == "__main__":
    simple_chatbot()



Slip 11:

1) Write a python program using mean end analysis algorithmproblem of transforming a string of lowercase letters into another string.


def mean_end_analysis(start, goal):
    current_state = list(start)
    goal_state = list(goal)
    steps = []

    while current_state != goal_state:
        for i in range(len(current_state)):
            if current_state[i] != goal_state[i]:
                current_state[i] = chr((ord(current_state[i]) - 97 + 1) % 26 + 97)
                steps.append(''.join(current_state))
       
        if current_state == goal_state:
            break

        steps.append(''.join(current_state))

    return steps

if __name__ == "__main__":
    start_string = "abcde"
    goal_string = "vwxyz"

    result = mean_end_analysis(start_string, goal_string)

    if result:
        print(f"Transformation steps from '{start_string}' to '{goal_string}':")
        for step in result:
            print(step)
    else:
        print(f"No transformation needed. The strings are already the same.")


Q.2) Write a Python program to solve water jug problem. Two jugs with capacity 4 gallon and 3 gallon are given with unlimited water supply respectively. The target is to achieve 2 gallon of water in second jug.


def water_jug_problem(capacity_jug1, capacity_jug2, target):
    def pour(jug1, jug2):
        # Pour water from jug1 to jug2
        if jug1 > 0 and jug2 < capacity_jug2:
            amount = min(jug1, capacity_jug2 - jug2)
            jug1 -= amount
            jug2 += amount
            yield jug1, jug2

        # Pour water from jug2 to jug1
        if jug2 > 0 and jug1 < capacity_jug1:
            amount = min(jug2, capacity_jug1 - jug1)
            jug2 -= amount
            jug1 += amount
            yield jug1, jug2

    def dfs(current_state, visited):
        if current_state[1] == target:
            return [current_state[0], current_state[1]]

        visited.add(current_state)

        for next_state in pour(*current_state):
            if next_state not in visited:
                result = dfs(next_state, visited)
                if result:
                    return [current_state[0], current_state[1]] + result

        return None

    initial_state = [0, 0]
    final_state = dfs(initial_state, set())

    if final_state:
        print(f"Solution found: {final_state[0]} gallons in the 4-gallon jug and {final_state[1]} gallons in the 3-gallon jug.")
    else:
        print("No solution found.")

if __name__ == "__main__":
    water_jug_problem(4, 3, 2)



Slip 12:

 


Write a python program to generate Calendar for the given month and year?


import calendar

def generate_calendar(year, month):
    cal = calendar.monthcalendar(year, month)
    month_name = calendar.month_name[month]

    print(f"Calendar for {month_name} {year}:")
    print(" Mo Tu We Th Fr Sa Su")

    for week in cal:
        for day in week:
            if day == 0:
                print("   ", end=" ")
            else:
                print(f"{day:2} ", end=" ")

        print()

if __name__ == "__main__":
    year = int(input("Enter the year: "))
    month = int(input("Enter the month (1-12): "))

    generate_calendar(year, month)





Q.2)Write a Python program to simulate 4-Queens problem


def is_safe(board, row, col):
    # Check if there is a queen in the same row
    if any(board[row][c] == 1 for c in range(col)):
        return False

    # Check upper diagonal on the left side
    if any(board[r][c] == 1 for r, c in zip(range(row, -1, -1), range(col, -1, -1))):
        return False

    # Check lower diagonal on the left side
    if any(board[r][c] == 1 for r, c in zip(range(row, len(board)), range(col, -1, -1))):
        return False

    return True

def solve_n_queens_util(board, col):
    if col >= len(board):
        return True

    for row in range(len(board)):
        if is_safe(board, row, col):
            board[row][col] = 1

            if solve_n_queens_util(board, col + 1):
                return True

            board[row][col] = 0

    return False

def solve_n_queens(n):
    board = [[0] * n for _ in range(n)]

    if solve_n_queens_util(board, 0):
        print("Solution found:")
        for row in board:
            print(" ".join("Q" if cell == 1 else "." for cell in row))
    else:
        print("No solution found.")

if __name__ == "__main__":
    solve_n_queens(4)


Slip 13 :


Q.1Write a Python program to implement Mini-Max Algorithm

import math

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def is_winner(board, player):
    for row in board:
        if all(cell == player for cell in row):
            return True

    for col in range(3):
        if all(board[row][col] == player for row in range(3)):
            return True

    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
        return True

    return False

def is_board_full(board):
    return all(cell != ' ' for row in board for cell in row)

def evaluate(board):
    if is_winner(board, 'X'):
        return 1
    elif is_winner(board, 'O'):
        return -1
    elif is_board_full(board):
        return 0
    else:
        return None

def minimax(board, depth, maximizing_player):
    score = evaluate(board)

    if score is not None:
        return score

    if maximizing_player:
        max_eval = -math.inf
        for i in range(3):
            for j in range(3):
                if board[i][j] == ' ':
                    board[i][j] = 'X'
                    eval = minimax(board, depth + 1, False)
                    board[i][j] = ' '
                    max_eval = max(max_eval, eval)
        return max_eval
    else:
        min_eval = math.inf
        for i in range(3):
            for j in range(3):
                if board[i][j] == ' ':
                    board[i][j] = 'O'
                    eval = minimax(board, depth + 1, True)
                    board[i][j] = ' '
                    min_eval = min(min_eval, eval)
        return min_eval

def find_best_move(board):
    best_val = -math.inf
    best_move = None

    for i in range(3):
        for j in range(3):
            if board[i][j] == ' ':
                board[i][j] = 'X'
                move_val = minimax(board, 0, False)
                board[i][j] = ' '

                if move_val > best_val:
                    best_move = (i, j)
                    best_val = move_val

    return best_move

def play_tic_tac_toe():
    board = [[' ' for _ in range(3)] for _ in range(3)]
    print_board(board)

    while True:
        # Player's move
        row, col = map(int, input("Enter your move (row col): ").split())
        if board[row][col] != ' ':
            print("Invalid move. Cell already occupied. Try again.")
            continue
        board[row][col] = 'O'
        print_board(board)

        # Check if player wins
        if is_winner(board, 'O'):
            print("Congratulations! You win!")
            break

        # Check if the board is full
        if is_board_full(board):
            print("It's a tie!")
            break

        # AI's move
        print("AI is making a move...")
        ai_row, ai_col = find_best_move(board)
        board[ai_row][ai_col] = 'X'
        print_board(board)

        # Check if AI wins
        if is_winner(board, 'X'):
            print("AI wins! Better luck next time.")
            break

        # Check if the board is full
        if is_board_full(board):
            print("It's a tie!")
            break

if __name__ == "__main__":
    play_tic_tac_toe()




Slip 14:

Write a python program to sort the sentence in alphabetical order?

def sort_sentence(sentence):
    words = sentence.split()
    sorted_words = sorted(words)
    sorted_sentence = ' '.join(sorted_words)
    return sorted_sentence

if __name__ == "__main__":
    input_sentence = input("Enter a sentence: ")
    result = sort_sentence(input_sentence)
    print("Sorted sentence:", result)


Write a Python program to simulate n-Queens problem.


def print_solution(board):
    for row in board:
        print(" ".join("Q" if cell else "." for cell in row))
    print("\n")

def is_safe(board, row, col, n):
    # Check if there is a queen in the same row
    if any(board[row][c] for c in range(col)):
        return False

    # Check upper diagonal on the left side
    if any(board[r][c] for r, c in zip(range(row, -1, -1), range(col, -1, -1))):
        return False

    # Check lower diagonal on the left side
    if any(board[r][c] for r, c in zip(range(row, n), range(col, -1, -1))):
        return False

    return True

def solve_n_queens_util(board, col, n):
    if col >= n:
        print_solution(board)
        return True

    res = False
    for i in range(n):
        if is_safe(board, i, col, n):
            board[i][col] = 1

            res = solve_n_queens_util(board, col + 1, n) or res

            board[i][col] = 0

    return res

def solve_n_queens(n):
    board = [[0] * n for _ in range(n)]

    if not solve_n_queens_util(board, 0, n):
        print(f"No solution for {n}-Queens.")

if __name__ == "__main__":
    n = int(input("Enter the value of N for N-Queens: "))
    solve_n_queens(n)



Slip 15:

Write a Program to Implement Monkey Banana Problem using Python


import random

class MonkeyBananaProblem:
    def __init__(self, rows, cols):
        self.rows = rows
        self.cols = cols
        self.monkey_position = (rows - 1, 0)
        self.banana_position = (0, cols - 1)
        self.bananas_collected = 0

    def move(self, direction):
        if direction == 'up' and self.monkey_position[0] > 0:
            self.monkey_position = (self.monkey_position[0] - 1, self.monkey_position[1])
        elif direction == 'down' and self.monkey_position[0] < self.rows - 1:
            self.monkey_position = (self.monkey_position[0] + 1, self.monkey_position[1])
        elif direction == 'left' and self.monkey_position[1] > 0:
            self.monkey_position = (self.monkey_position[0], self.monkey_position[1] - 1)
        elif direction == 'right' and self.monkey_position[1] < self.cols - 1:
            self.monkey_position = (self.monkey_position[0], self.monkey_position[1] + 1)

        if self.monkey_position == self.banana_position:
            self.bananas_collected += 1
            self.place_banana()

    def place_banana(self):
        self.banana_position = (random.randint(0, self.rows - 1), random.randint(0, self.cols - 1))

    def print_state(self):
        for i in range(self.rows):
            for j in range(self.cols):
                if (i, j) == self.monkey_position:
                    print('M', end=' ')
                elif (i, j) == self.banana_position:
                    print('B', end=' ')
                else:
                    print('.', end=' ')
            print()

if __name__ == "__main__":
    rows = int(input("Enter the number of rows in the room: "))
    cols = int(input("Enter the number of columns in the room: "))

    monkey_banana_problem = MonkeyBananaProblem(rows, cols)

    while True:
        monkey_banana_problem.print_state()
        print(f"Bananas collected: {monkey_banana_problem.bananas_collected}")

        if monkey_banana_problem.monkey_position == monkey_banana_problem.banana_position:
            print("Congratulations! Monkey reached the banana.")
            break

        direction = input("Enter the direction to move (up/down/left/right): ")
        monkey_banana_problem.move(direction.lower())



Write a program to implement Iterative Deepening DFS algorithm.

def iterative_deepening_dfs(root, goal_state, max_depth):
    for depth in range(max_depth + 1):
        result = depth_limited_dfs(root, goal_state, depth)
        if result is not None:
            return result
    return None

def depth_limited_dfs(node, goal_state, depth):
    if depth == 0 and node == goal_state:
        return node
    elif depth > 0:
        for child_state in generate_children(node):
            result = depth_limited_dfs(child_state, goal_state, depth - 1)
            if result is not None:
                return result
    return None

def generate_children(state):
    # Modify this function based on your specific problem to generate children
    # For demonstration purposes, let's consider a simple problem of generating children for integers
    return [state + 1, state - 1]

def iterative_deepening_dfs_without_class(initial_state, goal_state, max_depth):
    for depth in range(max_depth + 1):
        result = depth_limited_dfs(initial_state, goal_state, depth)
        if result is not None:
            return result
    return None

if __name__ == "__main__":
    initial_state = 0
    goal_state = 5
    max_depth = 10

    result = iterative_deepening_dfs_without_class(initial_state, goal_state, max_depth)

    if result is not None:
        print("Goal state found:", result)
    else:
        print("Goal state not found within the maximum depth.")



OR

class Node:
    def __init__(self, state, parent=None):
        self.state = state
        self.parent = parent

def iterative_deepening_dfs(root, goal_state, max_depth):
    for depth in range(max_depth + 1):
        result = depth_limited_dfs(root, goal_state, depth)
        if result is not None:
            return result
    return None

def depth_limited_dfs(node, goal_state, depth):
    if depth == 0 and node.state == goal_state:
        return node
    elif depth > 0:
        for child_state in generate_children(node.state):
            child_node = Node(child_state, node)
            result = depth_limited_dfs(child_node, goal_state, depth - 1)
            if result is not None:
                return result
    return None

def generate_children(state):
    # Modify this function based on your specific problem to generate children
    # For demonstration purposes, let's consider a simple problem of generating children for integers
    return [state + 1, state - 1]

def print_solution(node):
    path = []
    while node is not None:
        path.insert(0, node.state)
        node = node.parent
    print("Solution path:", path)

if __name__ == "__main__":
    initial_state = 0
    goal_state = 5
    max_depth = 10

    root = Node(initial_state)
    result_node = iterative_deepening_dfs(root, goal_state, max_depth)

    if result_node is not None:
        print("Goal state found!")
        print_solution(result_node)
    else:
        print("Goal state not found within the maximum depth.")




Slip 16:

Write a Program to Implement Tower of Hanoi using Python


def tower_of_hanoi(n, source, target, auxiliary):
    if n > 0:
        # Move n-1 disks from source to auxiliary peg using target peg
        tower_of_hanoi(n - 1, source, auxiliary, target)

        # Move the nth disk from source to target peg
        print(f"Move disk {n} from {source} to {target}")

        # Move the n-1 disks from auxiliary peg to target peg using source peg
        tower_of_hanoi(n - 1, auxiliary, target, source)

if __name__ == "__main__":
    num_disks = int(input("Enter the number of disks: "))

    tower_of_hanoi(num_disks, 'A', 'C', 'B')



Write a Python program to solve tic-tac-toe problem


def check_winner(board):
    # Check rows
    for row in board:
        if all(cell == 'X' for cell in row):
            return 'X'
        elif all(cell == 'O' for cell in row):
            return 'O'

    # Check columns
    for col in range(3):
        if all(board[row][col] == 'X' for row in range(3)):
            return 'X'
        elif all(board[row][col] == 'O' for row in range(3)):
            return 'O'

    # Check diagonals
    if all(board[i][i] == 'X' for i in range(3)) or all(board[i][2 - i] == 'X' for i in range(3)):
        return 'X'
    elif all(board[i][i] == 'O' for i in range(3)) or all(board[i][2 - i] == 'O' for i in range(3)):
        return 'O'

    return None

def check_tie(board):
    return all(cell != ' ' for row in board for cell in row)

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def tic_tac_toe():
    board = [[' ' for _ in range(3)] for _ in range(3)]
    player = 'X'

    while True:
        print_board(board)
        row, col = map(int, input(f"Player {player}, enter your move (row col): ").split())

        if board[row][col] == ' ':
            board[row][col] = player
        else:
            print("Invalid move. Cell already occupied. Try again.")
            continue

        winner = check_winner(board)
        if winner:
            print_board(board)
            print(f"Player {winner} wins!")
            break

        if check_tie(board):
            print_board(board)
            print("It's a tie!")
            break

        player = 'O' if player == 'X' else 'X'

if __name__ == "__main__":
    tic_tac_toe()



Slip 17:


Python program that demonstrates the hill climbing algorithm to find the maximum of a mathematical function. 

import math

def hill_climbing(initial_x, step_size, max_iterations):
    current_x = initial_x

    for _ in range(max_iterations):
        current_value = objective_function(current_x)
        next_x = current_x + step_size
        next_value = objective_function(next_x)

        if next_value > current_value:
            current_x = next_x
        else:
            break

    return current_x, objective_function(current_x)

def objective_function(x):
    # Example mathematical function: f(x) = -x^2 + 5x + 10
    return -(x ** 2) + 5 * x + 10

if __name__ == "__main__":
    initial_x = float(input("Enter the initial value of x: "))
    step_size = float(input("Enter the step size: "))
    max_iterations = int(input("Enter the maximum number of iterations: "))

    result_x, result_value = hill_climbing(initial_x, step_size, max_iterations)

    print("\nHill Climbing Results:")
    print(f"Optimal x: {result_x}")
    print(f"Optimal value: {result_value}")




Python program that demonstrates the hill climbing algorithm to find the maximum of a mathematical function. 


def objective_function(x):
    return -(x ** 4) + 4 * (x ** 3) - 6 * (x ** 2) + 4 * x

def hill_climbing(initial_x, step_size, max_iterations):
    current_x = initial_x

    for _ in range(max_iterations):
        current_value = objective_function(current_x)
        next_x = current_x + step_size
        next_value = objective_function(next_x)

        if next_value > current_value:
            current_x = next_x
        else:
            break

    return current_x, objective_function(current_x)

if __name__ == "__main__":
    initial_x = float(input("Enter the initial value of x: "))
    step_size = float(input("Enter the step size: "))
    max_iterations = int(input("Enter the maximum number of iterations: "))

    result_x, result_value = hill_climbing(initial_x, step_size, max_iterations)

    print("\nHill Climbing Results:")
    print(f"Optimal x: {result_x}")
    print(f"Optimal value: {result_value}")




Slip 18:


Write a python program to remove stop words for a given passage from a text file using NLTK?. [

Install NLTK if you haven't already:

bash
Copy code
pip install nltk
Create a text file with the passage.

Use the following Python program:


import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

nltk.download('stopwords')
nltk.download('punkt')

def remove_stop_words(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as file:
        passage = file.read()

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

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

    with open(output_file, 'w', encoding='utf-8') as file:
        file.write(" ".join(filtered_words))

if __name__ == "__main__":
    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)



 Implement a system that performs arrangement of some set of objects in a room. Assume that you have only 5 rectangular, 4 square-shaped objects. Use A* approach for the placement of the objects in room for efficient space utilisation. Assume suitable heuristic, and dimensions of objects and rooms. (Informed Search)



import heapq

class State:
    def __init__(self, room, remaining_rectangular, remaining_square, cost, heuristic):
        self.room = room
        self.remaining_rectangular = remaining_rectangular
        self.remaining_square = remaining_square
        self.cost = cost
        self.heuristic = heuristic

def is_valid_move(room, obj_type, row, col):
    rows, cols = len(room), len(room[0])

    if obj_type == 'rectangular':
        return row + 1 < rows and col + 2 < cols and all(room[row + i][col + j] == 0 for i in range(2) for j in range(3))
    elif obj_type == 'square':
        return row + 1 < rows and col + 1 < cols and all(room[row + i][col + j] == 0 for i in range(2) for j in range(2))

def apply_move(room, obj_type, row, col):
    if obj_type == 'rectangular':
        for i in range(2):
            for j in range(3):
                room[row + i][col + j] = 1
    elif obj_type == 'square':
        for i in range(2):
            for j in range(2):
                room[row + i][col + j] = 1

def heuristic(room, remaining_rectangular, remaining_square):
    return remaining_rectangular * 6 + remaining_square * 4  # Heuristic based on the number of empty cells

def a_star_search():
    rows, cols = 6, 6
    initial_room = [[0] * cols for _ in range(rows)]

    initial_state = State(initial_room, 5, 4, 0, heuristic(initial_room, 5, 4))
    heap = [(initial_state.cost + initial_state.heuristic, initial_state)]
    visited = set()

    while heap:
        _, current_state = heapq.heappop(heap)

        if current_state.remaining_rectangular == 0 and current_state.remaining_square == 0:
            return current_state.room

        if tuple(map(tuple, current_state.room)) in visited:
            continue

        visited.add(tuple(map(tuple, current_state.room)))

        for i in range(rows):
            for j in range(cols):
                for obj_type in ['rectangular', 'square']:
                    if is_valid_move(current_state.room, obj_type, i, j):
                        new_room = [row[:] for row in current_state.room]
                        apply_move(new_room, obj_type, i, j)
                        new_remaining_rectangular = current_state.remaining_rectangular - (1 if obj_type == 'rectangular' else 0)
                        new_remaining_square = current_state.remaining_square - (1 if obj_type == 'square' else 0)
                        new_cost = current_state.cost + 1
                        new_heuristic = heuristic(new_room, new_remaining_rectangular, new_remaining_square)
                        new_state = State(new_room, new_remaining_rectangular, new_remaining_square, new_cost, new_heuristic)
                        heapq.heappush(heap, (new_state.cost + new_state.heuristic, new_state))

    return None

def print_room(room):
    for row in room:
        print(" ".join(map(str, row)))

if __name__ == "__main__":
    final_room = a_star_search()

    if final_room:
        print("Optimal arrangement:")
        print_room(final_room)
    else:
        print("No solution found.")



Slip 19:



Q.1)Write a program to implement Hangman game using python. [10 Marks] Description: Hangman is a classic word-guessing game. The user should guess the word correctly by entering alphabets of the user choice. The Program will get input as single alphabet from the user and it will matchmaking with the alphabets in the original 


import random

def hangman():
    secret_word = random.choice(["python", "hangman", "programming", "computer", "science", "algorithm"])
    guessed_letters, attempts = set(), 6
   
    while attempts > 0 and set(secret_word) > guessed_letters:
        print("Current word:", ''.join(letter if letter in guessed_letters else '_' for letter in secret_word))
        guess = input("Guess a letter: ").lower()
        guessed_letters.add(guess)
        attempts -= guess not in secret_word

    print(f"{'Congratulations!' if set(secret_word) <= guessed_letters else 'Sorry, you ran out of attempts. The word was: ' + secret_word}")

if __name__ == "__main__":
    hangman()

OR

import random

def choose_word():
    words = ["python", "hangman", "programming", "computer", "nil", "algorithm", "shreya"]
    return random.choice(words)

def display_word(word, guessed_letters):
    display = ""
    for letter in word:
        if letter in guessed_letters:
            display += letter
        else:
            display += "_"
    return display

def hangman():
    print("Welcome to Hangman!")
    secret_word = choose_word()
    guessed_letters = []
    attempts_left = 6

    while attempts_left > 0:
        print("\nCurrent Word:", display_word(secret_word, guessed_letters))
        guess = input("Enter a letter: ").lower()

        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a single alphabet.")
            continue

        if guess in guessed_letters:
            print("You've already guessed that letter. Try again.")
            continue

        guessed_letters.append(guess)

        if guess not in secret_word:
            attempts_left -= 1
            print(f"Incorrect! Attempts left: {attempts_left}")
        else:
            print("Correct guess!")

        if all(letter in guessed_letters for letter in secret_word):
            print("\nCongratulations! You guessed the word:", secret_word)
            break

    if attempts_left == 0:
        print("\nOut of attempts! The word was:", secret_word)

if __name__ == "__main__":
    hangman()


Write a Python program to implement A* algorithm. Refer the following graph as an Input for the program.

import heapq

class Graph:
    def __init__(self):
        self.graph = {}

    def add_edge(self, node, neighbors):
        self.graph[node] = neighbors

def astar(graph, start, goal):
    heap = [(0, start, [])]
    visited = set()

    while heap:
        (cost, current_node, path) = heapq.heappop(heap)

        if current_node in visited:
            continue

        path = path + [current_node]

        if current_node == goal:
            return path

        visited.add(current_node)

        for neighbor, neighbor_cost in graph.graph[current_node].items():
            heapq.heappush(heap, (cost + neighbor_cost, neighbor, path))

    return None

if __name__ == "__main__":
    # Example graph structure
    example_graph = Graph()
    example_graph.add_edge("A", {"B": 5, "C": 3})
    example_graph.add_edge("B", {"D": 2})
    example_graph.add_edge("C", {"D": 1})
    example_graph.add_edge("D", {"E": 4})

    start_node = "A"
    goal_node = "E"

    result = astar(example_graph, start_node, goal_node)

    if result:
        print(f"Optimal path from {start_node} to {goal_node}: {result}")
    else:
        print(f"No path found from {start_node} to {goal_node}.")


Slip 20:

 Build a bot which provides all the information related to you in college

pip install chatterbot chatterbot_corpus


from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

# Create a chat bot
college_bot = ChatBot("CollegeBot")

# Create a new trainer for the chat bot
trainer = ChatterBotCorpusTrainer(college_bot)

# Train the chat bot on the English language corpus data
trainer.train("chatterbot.corpus.english")

# Additional training data for college-related information
trainer.train([
    "What is your college?",
    "I am a virtual assistant and don't belong to any specific college.",
    "Tell me about your college life.",
    "I don't have a physical presence, so I don't experience college life.",
    # Add more training data related to your college
])

# Create a function to interact with the bot
def chat_with_college_bot():
    print("College Bot: Hi! I'm your College Bot. Ask me anything about college.")
    while True:
        user_input = input("You: ")
        if user_input.lower() == 'exit':
            print("College Bot: Goodbye!")
            break
        response = college_bot.get_response(user_input)
        print("College Bot:", response)

if __name__ == "__main__":
    chat_with_college_bot()

 


Write a Python program to implement Mini-Max Algorithm


# Tic-Tac-Toe Board Representation
board = [
    [' ', ' ', ' '],
    [' ', ' ', ' '],
    [' ', ' ', ' ']
]

# Constants for player symbols
PLAYER_X = 'X'
PLAYER_O = 'O'
EMPTY = ' '

# Function to print the current state of the board
def print_board():
    for row in board:
        print('|'.join(row))
        print('-----')

# Function to check if the current player has won
def is_winner(player):
    # Check rows and columns
    for i in range(3):
        if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
            return True
    # Check diagonals
    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
        return True
    return False

# Function to check if the board is full
def is_board_full():
    return all(board[i][j] != EMPTY for i in range(3) for j in range(3))

# Function to evaluate the board for Mini-Max algorithm
def evaluate_board():
    if is_winner(PLAYER_X):
        return 1
    elif is_winner(PLAYER_O):
        return -1
    elif is_board_full():
        return 0
    else:
        return None

# Mini-Max Algorithm
def minimax(depth, is_maximizing):
    score = evaluate_board()

    if score is not None:
        return score

    if is_maximizing:
        best_score = float('-inf')
        for i in range(3):
            for j in range(3):
                if board[i][j] == EMPTY:
                    board[i][j] = PLAYER_X
                    score = minimax(depth + 1, False)
                    board[i][j] = EMPTY
                    best_score = max(score, best_score)
        return best_score
    else:
        best_score = float('inf')
        for i in range(3):
            for j in range(3):
                if board[i][j] == EMPTY:
                    board[i][j] = PLAYER_O
                    score = minimax(depth + 1, True)
                    board[i][j] = EMPTY
                    best_score = min(score, best_score)
        return best_score

# Function to find the best move for the AI
def find_best_move():
    best_score = float('-inf')
    best_move = None

    for i in range(3):
        for j in range(3):
            if board[i][j] == EMPTY:
                board[i][j] = PLAYER_X
                score = minimax(0, False)
                board[i][j] = EMPTY

                if score > best_score:
                    best_score = score
                    best_move = (i, j)

    return best_move

# Function to play the game
def play_game():
    while True:
        print_board()

        # Player's move
        row = int(input("Enter the row (0, 1, or 2): "))
        col = int(input("Enter the column (0, 1, or 2): "))

        if board[row][col] != EMPTY:
            print("Cell already occupied. Try again.")
            continue

        board[row][col] = PLAYER_O

        # Check if player wins
        if is_winner(PLAYER_O):
            print_board()
            print("Player (O) wins!")
            break

        # Check for a tie
        if is_board_full():
            print_board()
            print("It's a tie!")
            break

        print_board()

        # AI's move
        print("AI's move:")
        best_move = find_best_move()
        board[best_move[0]][best_move[1]] = PLAYER_X

        # Check if AI wins
        if is_winner(PLAYER_X):
            print_board()
            print("AI (X) wins!")
            break

        # Check for a tie
        if is_board_full():
            print_board()
            print("It's a tie!")
            break

if __name__ == "__main__":
    play_game()



Slip 21:


Q.1) Write a python program to remove punctuations from the given string? .[ 10 marks ] 

import string

def remove_punctuation(input_string):
    # Get the set of punctuation characters
    punctuations = set(string.punctuation)

    # Remove punctuations from the input string
    result_string = ''.join(char for char in input_string if char not in punctuations)

    return result_string

if __name__ == "__main__":
    input_string = input("Enter a string with punctuations: ")

    result = remove_punctuation(input_string)

    print("String without punctuations:", result)

Enter a string with punctuations: Swapnil!learn,with,nil

String without punctuations: Swapnillearnwithnil




Write a Python program for the following Cryptarithmetic problems. 

GO + TO = OUT

from itertools import permutations

def is_valid_assignment(assignment):
    g, o, t, u = assignment['G'], assignment['O'], assignment['T'], assignment['U']
    return g != 0 and t != 0 and (g * 10 + o + t * 10 + o == u * 100 + t * 10 + o)

def solve_cryptarithmetic():
    letters = ['G', 'O', 'T', 'U']
    digits = range(10)
    valid_assignments = []

    for perm in permutations(digits, len(letters)):
        assignment = dict(zip(letters, perm))
        if is_valid_assignment(assignment):
            valid_assignments.append(assignment)

    return valid_assignments

def print_solutions(solutions):
    for solution in solutions:
        print("  {}{} + {}{} = {}{}".format(
            solution['G'], solution['O'],
            solution['T'], solution['O'],
            solution['O'], solution['U']
        ))

if __name__ == "__main__":
    print("Solving Cryptarithmetic Problem: GO + TO = OUT")
   
    solutions = solve_cryptarithmetic()

    if solutions:
        print("Valid solutions found:")
        print_solutions(solutions)
    else:
        print("No solution found.")



Slip 22:

1) Write a Program to Implement Alpha-Beta Pruning using Python


INFINITY = float('inf')
NEG_INFINITY = float('-inf')

def is_winner(board, player):
    # Check rows and columns
    for i in range(3):
        if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
            return True
    # Check diagonals
    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
        return True
    return False

def is_board_full(board):
    return all(board[i][j] != ' ' for i in range(3) for j in range(3))

def evaluate(board):
    if is_winner(board, 'X'):
        return 1
    elif is_winner(board, 'O'):
        return -1
    elif is_board_full(board):
        return 0
    else:
        return None

def alpha_beta_pruning(board, depth, alpha, beta, maximizing_player):
    score = evaluate(board)

    if score is not None:
        return score

    if maximizing_player:
        max_eval = NEG_INFINITY
        for i in range(3):
            for j in range(3):
                if board[i][j] == ' ':
                    board[i][j] = 'X'
                    eval = alpha_beta_pruning(board, depth + 1, alpha, beta, False)
                    board[i][j] = ' '
                    max_eval = max(max_eval, eval)
                    alpha = max(alpha, eval)
                    if beta <= alpha:
                        break
        return max_eval
    else:
        min_eval = INFINITY
        for i in range(3):
            for j in range(3):
                if board[i][j] == ' ':
                    board[i][j] = 'O'
                    eval = alpha_beta_pruning(board, depth + 1, alpha, beta, True)
                    board[i][j] = ' '
                    min_eval = min(min_eval, eval)
                    beta = min(beta, eval)
                    if beta <= alpha:
                        break
        return min_eval

def find_best_move(board):
    best_val = NEG_INFINITY
    best_move = (-1, -1)

    for i in range(3):
        for j in range(3):
            if board[i][j] == ' ':
                board[i][j] = 'X'
                move_val = alpha_beta_pruning(board, 0, NEG_INFINITY, INFINITY, False)
                board[i][j] = ' '
                if move_val > best_val:
                    best_move = (i, j)
                    best_val = move_val

    return best_move

def print_board(board):
    for row in board:
        print('|'.join(row))
        print('-----')

if __name__ == "__main__":
    board = [[' ' for _ in range(3)] for _ in range(3)]

    while True:
        print_board(board)

        # Player's move
        row = int(input("Enter the row (0, 1, or 2): "))
        col = int(input("Enter the column (0, 1, or 2): "))

        if board[row][col] != ' ':
            print("Cell already occupied. Try again.")
            continue

        board[row][col] = 'O'

        # Check if player wins
        if is_winner(board, 'O'):
            print_board(board)
            print("Player (O) wins!")
            break

        # Check for a tie
        if is_board_full(board):
            print_board(board)
            print("It's a tie!")
            break

        print_board(board)

        # AI's move
        print("AI's move:")
        best_move = find_best_move(board)
        board[best_move[0]][best_move[1]] = 'X'

        # Check if AI wins
        if is_winner(board, 'X'):
            print_board(board)
            print("AI (X) wins!")
            break

        # Check for a tie
        if is_board_full(board):
            print_board(board)
            print("It's a tie!")
            break




Write a Python program to implement Simple Chatbot.


import random

def simple_chatbot():
    print("Hello! I'm a Simple Chatbot. You can type 'bye' to exit.")

    while True:
        user_input = input("You: ").lower()

        if user_input == 'bye':
            print("Chatbot: Goodbye! Have a great day.")
            break
        elif 'how are you' in user_input:
            print("Chatbot: I'm doing well, thank you!")
        elif 'your name' in user_input:
            print("Chatbot: I'm just a simple chatbot.")
        elif 'joke' in user_input:
            jokes = [
                "Why did the scarecrow win an award? Because he was outstanding in his field!",
                "What did one wall say to the other wall? I'll meet you at the corner.",
                "Why don't scientists trust atoms? Because they make up everything!"
            ]
            print(f"Chatbot: {random.choice(jokes)}")
        else:
            print("Chatbot: I'm sorry, I didn't understand that.")

if __name__ == "__main__":
    simple_chatbot()



Slip 23:



Write a Program to Implement Tower of Hanoi using Python


def tower_of_hanoi(n, source, target, auxiliary):
    if n > 0:
        # Move n-1 disks from source to auxiliary peg using target peg
        tower_of_hanoi(n - 1, source, auxiliary, target)

        # Move the nth disk from source to target peg
        print(f"Move disk {n} from {source} to {target}")

        # Move the n-1 disks from auxiliary peg to target peg using source peg
        tower_of_hanoi(n - 1, auxiliary, target, source)

if __name__ == "__main__":
    num_disks = int(input("Enter the number of disks: "))

    tower_of_hanoi(num_disks, 'A', 'C', 'B')




Write a Python program for the following Cryptarithmetic problems SEND + MORE = MONEY 

from itertools import permutations

def is_valid_assignment(assignment):
    s, e, n, d, m, o, r, y = assignment['S'], assignment['E'], assignment['N'], assignment['D'], assignment['M'], assignment['O'], assignment['R'], assignment['Y']
    return s != 0 and m != 0 and (s * 1000 + e * 100 + n * 10 + d + m * 1000 + o * 100 + r * 10 + e == m * 10000 + o * 1000 + n * 100 + e * 10 + y)

def solve_cryptarithmetic():
    letters = ['S', 'E', 'N', 'D', 'M', 'O', 'R', 'Y']
    digits = range(10)
    valid_assignments = []

    for perm in permutations(digits, len(letters)):
        assignment = dict(zip(letters, perm))
        if is_valid_assignment(assignment):
            valid_assignments.append(assignment)

    return valid_assignments

def print_solutions(solutions):
    for solution in solutions:
        print("  {}{}{}{} + {}{}{} = {}{}{}{}{}".format(
            solution['S'], solution['E'], solution['N'], solution['D'],
            solution['M'], solution['O'], solution['R'],
            solution['M'], solution['O'], solution['N'], solution['E'], solution['Y']
        ))

if __name__ == "__main__":
    print("Solving Cryptarithmetic Problem: SEND + MORE = MONEY")
   
    solutions = solve_cryptarithmetic()

    if solutions:
        print("Valid solutions found:")
        print_solutions(solutions)
    else:
        print("No solution found.")



Slip 24:

1)Write a python program to sort the sentence in alphabetical order?

def sort_sentence(sentence):
    words = sentence.split()
    sorted_words = sorted(words)
    sorted_sentence = ' '.join(sorted_words)
    return sorted_sentence

if __name__ == "__main__":
    input_sentence = input("Enter a sentence: ")
    result = sort_sentence(input_sentence)
    print("Sorted Sentence:", result)

Write a Python program for the following Cryptorithmetic problems CROSS+ROADS = DANGER




Slip 25:

Build a bot which provides all the information related to you in college

from itertools import permutations

def is_valid_assignment(assignment):
    cross = assignment['C']*10000 + assignment['R']*1000 + assignment['O']*100 + assignment['S']*10 + assignment['S']
    roads = assignment['R']*10000 + assignment['O']*1000 + assignment['A']*100 + assignment['D']*10 + assignment['S']
    danger = assignment['D']*100000 + assignment['A']*10000 + assignment['N']*1000 + assignment['G']*100 + assignment['E']*10 + assignment['R']

    return cross + roads == danger

def solve_cryptarithmetic():
    letters = ['C', 'R', 'O', 'S', 'A', 'D', 'N', 'G', 'E']
    digits = range(10)
    valid_assignments = []

    for perm in permutations(digits, len(letters)):
        assignment = dict(zip(letters, perm))
        if is_valid_assignment(assignment):
            valid_assignments.append(assignment)

    return valid_assignments

def print_solutions(solutions):
    for solution in solutions:
        print("  {}{}{}{}{} + {}{}{}{}{} = {}{}{}{}{}{}".format(
            solution['C'], solution['R'], solution['O'], solution['S'], solution['S'],
            solution['R'], solution['O'], solution['A'], solution['D'], solution['S'],
            solution['D'], solution['A'], solution['N'], solution['G'], solution['E'], solution['R']
        ))

if __name__ == "__main__":
    print("Solving Cryptarithmetic Problem: CROSS + ROADS = DANGER")
   
    solutions = solve_cryptarithmetic()

    if solutions:
        print("Valid solutions found:")
        print_solutions(solutions)
    else:
        print("No solution found.")



Slip 25:

Build a bot which provides all the information related to you in college


pip install chatterbot


from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

# Create a chat bot
college_bot = ChatBot("CollegeBot")

# Create a new trainer for the chat bot
trainer = ChatterBotCorpusTrainer(college_bot)

# Train the chat bot on the English language corpus data
trainer.train("chatterbot.corpus.english")

# Additional training data for college-related information
trainer.train([
    "What is your college?",
    "I am a virtual assistant and don't belong to any specific college.",
    "Tell me about your college life.",
    "I don't have a physical presence, so I don't experience college life.",
    # Add more training data related to your college
])

# Function to interact with the bot
def chat_with_college_bot():
    print("College Bot: Hi! I'm your College Bot. Ask me anything about college.")
    while True:
        user_input = input("You: ")
        if user_input.lower() == 'exit':
            print("College Bot: Goodbye!")
            break
        response = college_bot.get_response(user_input)
        print("College Bot:", response)

if __name__ == "__main__":
    chat_with_college_bot()



Write a Python program to solve 8-puzzle problem.


import heapq
from typing import List, Tuple

class PuzzleState:
    def __init__(self, board: List[List[int]]):
        self.board = board
        self.size = len(board)
        self.goal = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]

    def __eq__(self, other):
        return self.board == other.board

    def __hash__(self):
        return hash(tuple(tuple(row) for row in self.board))

    def __lt__(self, other):
        return False

    def find_blank(self) -> Tuple[int, int]:
        for i in range(self.size):
            for j in range(self.size):
                if self.board[i][j] == 0:
                    return i, j

    def is_goal(self) -> bool:
        return self.board == self.goal

    def generate_successors(self) -> List["PuzzleState"]:
        successors = []
        i, j = self.find_blank()

        # Check possible moves: left, right, up, down
        moves = [(0, -1), (0, 1), (-1, 0), (1, 0)]

        for move in moves:
            ni, nj = i + move[0], j + move[1]

            if 0 <= ni < self.size and 0 <= nj < self.size:
                new_board = [row.copy() for row in self.board]
                new_board[i][j], new_board[ni][nj] = new_board[ni][nj], new_board[i][j]
                successors.append(PuzzleState(new_board))

        return successors

def manhattan_distance(state: PuzzleState) -> int:
    distance = 0
    for i in range(state.size):
        for j in range(state.size):
            value = state.board[i][j]
            if value != 0:
                goal_i, goal_j = divmod(value - 1, state.size)
                distance += abs(i - goal_i) + abs(j - goal_j)
    return distance

def a_star_search(initial_state: PuzzleState) -> List[PuzzleState]:
    heap = [(0, 0, initial_state)]
    visited = set()

    while heap:
        _, cost, current_state = heapq.heappop(heap)

        if current_state.is_goal():
            path = []
            while current_state:
                path.append(current_state)
                current_state = current_state.parent
            return path[::-1]

        if current_state not in visited:
            visited.add(current_state)

            for successor in current_state.generate_successors():
                if successor not in visited:
                    successor.cost = cost + 1
                    successor.heuristic = manhattan_distance(successor)
                    successor.parent = current_state
                    heapq.heappush(heap, (successor.cost + successor.heuristic, successor.cost, successor))

    return []

def print_solution(solution: List[PuzzleState]):
    for state in solution:
        for row in state.board:
            print(" ".join(map(str, row)))
        print()

if __name__ == "__main__":
    initial_board = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 0]
    ]

    initial_state = PuzzleState(initial_board)
    initial_state.cost = 0
    initial_state.heuristic = manhattan_distance(initial_state)

    solution = a_star_search(initial_state)

    if solution:
        print("Solution found:")
        print_solution(solution)
    else:
        print("No solution found.")










s



















s


Comments

Popular posts from this blog

Practical slips programs : Machine Learning

Full Stack Developement Practical Slips Programs

MCS Advanced Database & Web Technology