SUBJECT: CS - 505 - MJP: Lab Course on CS - 502 - MJ (Artificial Intelligence) Assignment 1 Q.1) Python program that demonstrates the hill climbing algorithm to find the maximum of a mathematical function. (For example f(x) = - x² + 4x) import random # Define the function def f(x): return - x**2 + 4*x # Hill Climbing Algorithm def hill_climb(func, x_start, step_size, max_iterations): current_x = x_start current_value = func(current_x) for i in range(max_iterations): # Generate a new candidate solution (neighbor) new_x = current_x + random.uniform( - step_size, step_size) new_value = func(new_x) # If the new solution is better, move to it if new_value > current_value: current_x = new_x current_value = new_value return current_x, current_value # Parameters x_start = random.uniform(0, 4) step_size = 0.1 max_iterations = 1000 best_x, best_value = hill_climb(f, x_start, step_size, max_iterations) print( "Function: f(x) = - x^2 + 4x") print(f"Starting point: {x_start:.4f}") print(f"Maximum value of function is approximately f({best_x:.4f}) = {best_value:.4f}") Output: Function: f(x) = - x^2 + 4x Starting point: 2.5376 Maximum value of function is approximately f(1.9998) = 3.9999 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] def dfs(graph, start, goal, visited=None): if visited is None: visited = [] visited.append(start) print(start, end=" ") if start == goal: return True for neighbor in graph[start]: if neighbor not in visited: if dfs( graph, neighbor, goal, visited): return True return False # Define the graph as an adjacency list graph = { 1: [2, 3], 2: [4, 5], 3: [6, 7], 4: [8], 5: [8], 6: [8], 7: [8], 8: [] } start_node = 1 goal_node = 8 print("Depth First Search Traversal:") found = dfs(graph, start_node, goal_node) if found: print(" \ nGoal node", goal_node, "found!") else: print(" \ nGoal node", goal_node, "not found.") Output: Depth First Search Traversal: 1 2 4 8 Goal node 8 found! SUBJECT: CS - 505 - MJP: Lab Course on CS - 502 - MJ (Artificial Intelligence) Assignment 2 Q.1) Write a Python program to generate Calendar for the given month and year. import calendar # Input month and year year = int(input("Enter year: ")) month = int(input("Enter month: ")) # Display the calendar print(" \ nCalendar for:", calendar.month_name[month], year) print(calendar.month(year, month)) Output: Enter year: 2025 Enter month: 11 Calendar for: November 2025 November 2025 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 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=7] def dfs(graph, start, goal, visited=None): if visited is None: visited = [] visited.append(start) print(start, end=" ") if start == goal: return True for neighbor in graph[start]: if neighbor not in visited: if dfs(graph, neighbor, goal, visited): return True return False # Define the graph as an adjacency list graph = { 1: [2, 3], 2: [4], 3: [5], 4: [6], 5: [4, 7], 6: [], 7: [] } start_node = 1 goal_node = 7 print("Depth First Search Traversal:") found = dfs(graph, start_node, goal_node) if found: print(" \ nGoal node", goal_node, "found!") else: print(" \ nGoal node", goal_node, "not found.") Output: Depth First Search Traversal: 1 2 4 6 3 5 7 Goal node 7 found! SUBJECT: CS - 505 - MJP: Lab Course on CS - 502 - MJ (Artificial Intelligence) Assignment 3 Q.1) Write a python program to remove punctuations from the given string # Define punctuation characters punctuations = '''!() - []{};:'" \ ,<>./?@#$%^&*_~''' # Input string my_str = input("Enter a string: ") # Remove punctuation characters no_punct = "" for char in my_str: if char not in punctuations: no_punct += char print("String without punctuation:", no_punct) Output: Enter a string: Hello!!! Welcome, to M.Sc.(CS) Practical Exam... String without punctuation: Hello Welcome to MScCS Practical Exam Q.2) 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] def dfs(graph, start, goal, visited=None): if visited is None: visited = [] visited.append(start) print(start, end=" ") if start == goal: return True for neighbor in graph[start]: if neighbor not in visited: if dfs(graph, neighbor, goal, visited): return True return False # Define the graph as an adjacency list graph = { 1: [2, 3], 2: [1, 4, 5], 3: [1, 4], 4: [2, 3, 7], 5: [2, 6, 7], 6: [5, 7], 7: [4, 5, 6] } start_node = 2 goal_node = 7 print("Depth First Search Traversal:") found = dfs(graph, start_node, goal_node) if found: print(" \ nGoal node", goal_node, "found!") else: print(" \ nGoal node", goal_node, "not found.") Output: Depth First Search Traversal: 2 1 3 4 7 Goal node 7 fou bd! SUBJECT: CS - 505 - MJP: Lab Course on CS - 502 - MJ (Artificial Intelligence) Assignment 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 match/making with the alphabets in the original word. import random # Configuration WORD_LIST = ['python', 'hangman', 'computer', 'science', 'programming', 'artificial', 'intelligence'] MAX_ATTEMPTS = 6 def choose_word(): """Selects a random word for the game.""" return random.choice(WORD_LIST) def display_board(word, guessed_letters): """Generates the string representation of the word progress.""" display = "" for letter in word: if letter in guessed_letters: display += letter + " " else: display += "_ " return display.strip() def hangman_game(): """Main game loop.""" word_to_guess = choose_word() guessed_letters = set() attempts_left = MAX_ATTEMPTS print("Welcome to Hangman!") print(f"The word has {len(word_to_guess)} letters.") while attempts_left > 0: current_display = display_board(word_to_guess, guessed_letters) # Display current status print(" \ n ------------------------------ ") print(f"Word: {current_display}") print(f"Attempts Left: {attempts_left}") print(f"Guessed: {', '.join(sorted(list(guessed_letters)))}") # Check Win condition if "_" not in current_display: print(f" \ n*** WIN! CONGRATULATIONS! The word was: {word_to_guess.upper()}") return # Get user input guess = input("Guess a letter: ").lower() if not guess.isalpha() or len(guess) != 1: print(" Invalid input. Enter a single letter.") continue if guess in guessed_letters: print(" Already guessed.") continue guessed_letters.add(guess) if guess in word_to_guess: print(" Correct!") else: attempts_left - = 1 print(" Incorrect!") # Loss condition print(" \ n ------------------------------ ") print("*** GAME OVER! ***") print(f"The word was: {word_to_guess.upper()}") if _name_ == "_main_": hangman_game() Output: Welcome to Hangman! The word has 8 letters. ------------------------------ Word: _ _ _ _ _ _ _ _ Attempts Left: 6 Guessed: Guess a letter: i Correct! ------------------------------ Word: _ _ _ _ _ _ _ i Attempts Left: 6 Guessed: i Guess a letter: o Incorrect! ------------------------------ Word: _ _ _ _ _ _ _ i Attempts Left: 5 Guessed: i, o Guess a letter: a Correct! ... (further guesses) ... ------------------------------ Word: P R O G R A M M I N G Attempts Left: 5 Guessed: a, g, i, m, n, p, r, o *** WIN! CONGRATULATIONS! The word was: PROGRAMMING 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] [20 Marks] from collections import deque def bfs(graph, start_node, goal_node): """ Implements the Breadth - First Search (BFS) algorithm. Returns the shortest path. """ if start_node == goal_node: return [start_node] # Queue for nodes (stores the nodes to be visited next) queue = deque([start_node]) # Set to track visited nodes visited = {start_node} # Dictionary to store the path (child: parent) parent_map = {start_node: None} print(f"Starting BFS from {start_node} to {goal_node}...") print("Nodes visited in order (Level by Level):", end=" ") while queue: current_node = queue.popleft() print(current_node, end=" ") # Explore neighbors for neighbor in graph.get(current_node, []): if neighbor not in visited: visited.add(neighbor) parent_map[neighbor] = current_node # Record the path # Check if the goal is reached if neighbor == goal_node: # Reconstruct the path by backtracking path = [] node = goal_node while node is not None: path.append(node) node = parent_map.get(node) print(f" \ nGoal node {goal_node} reached!") return path[:: - 1] # Return the path from start to goal # Enqueue the neighbor queue.append(neighbor) return "Goal node not reachable" # The graph from the image, represented as an adjacency list # Assuming an UNDIRECTED graph: GRAPH_ADJACENCY = { 1: [2, 3, 4], 2: [1, 5], 3: [1, 6], 4: [1, 6], 5: [2, 7], 6: [3, 4, 7, 8], 7: [5, 6, 8], 8: [6, 7] } start_node = 1 goal_node = 8 if _name_ == "_main_": shortest_path = bfs(GRAPH_ADJACENCY, start_node, goal_node) print("Shortest Path:") print(shortest_path) Output: Starting BFS from 1 to 8... Nodes visited in order (Level by Level): 1 2 3 4 5 6 Goal node 8 reached! Shortest Path: [1, 3, 6, 8] SUBJECT: CS - 505 - MJP: Lab Course on CS - 502 - MJ (Artificial Intelligence) Assignment 5 Q.1) Write a python program to implement Lemmatization using NLTK. [10 Marks] import nltk from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize # Ensure necessary NLTK data is downloaded (run once) try: WordNetLemmatizer() except LookupError: # Download required data if not already present print("Downloading NLTK resources (punkt, wordnet)...") nltk.download('punkt') nltk.download('wordnet') def lemmatize_text(text): """ Tokenizes the input text and applies lemmatization to each word. Lemmatization reduces words to their base or dictionary form (lemma). """ lemmatizer = WordNetLemmatizer() # 1. Tokenize the text into individual words words = word_tokenize(text) # 2. Lemmatize each token lemmatized_words = [lemmatizer.lemmatize(word) for word in words] # 3. Join the words back into a sentence lemmatized_text = " ".join(lemmatized_words) return lemmatized_text, words, lemmatized_words # Input Example input_text = "The quick brown foxes were running and jumped over the sleeping dogs. She is having great ideas." if _name_ == "_main_": print(f"Original Text: {input_text}") # Run the function final_text, tokens, lemmas = lemmatize_text(input_text) # Print results in a readable format print(" \ n --- Results --- ") print(f"Tokenized Words: {tokens}") print(f"Lemmatized Words: {lemmas}") print(f" \ nLemmatized Text: {final_text}") Output: Original Text: The quick brown foxes were running and jumped over the sleeping dogs. She is having great ideas. Downloading NLTK resources (punkt, wordnet)... # (This appears only on first run)