0% found this document useful (0 votes)
12 views23 pages

AI Lab Practical Code Examples in Python

Uploaded by

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

AI Lab Practical Code Examples in Python

Uploaded by

Natasha Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to AI using Python

Natasha Singh

June 29, 2025

This document has the code snippets for all the Lab Manual Questions for
Intro to AI Lab using Python.

1
2025 Introduction to AI using Python

Intro to AI Practical Questions with Answer Code


1. Write a Python program to simulate a basic chatbot that responds with pre-
defined answers.

def chatbot_response(user_input):
responses = {
"hello": "Hi there!",
"how are you": "I’m just a bot, but I’m doing fine!",
"bye": "Goodbye!",
"name": "I’m a simple chatbot created with Python."
}
return [Link](user_input.lower(), "Sorry, I don’t understand that.")

while True:
user_input = input("You: ")
if user_input.lower() == "exit":
break
print("Bot:", chatbot_response(user_input))

2. Implement a simple Tic-Tac-Toe game where two players can play against
each other.

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

def check_win(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 play_game():
board = [[" "]*3 for _ in range(3)]
player = "X"
for turn in range(9):
print_board(board)
row = int(input(f"Player {player}, enter row (0-2): "))

2
2025 Introduction to AI using Python

col = int(input(f"Player {player}, enter col (0-2): "))


if board[row][col] == " ":
board[row][col] = player
if check_win(board, player):
print_board(board)
print(f"Player {player} wins!")
return
player = "O" if player == "X" else "X"
else:
print("Invalid move. Try again.")
print_board(board)
print("It’s a draw!")

play_game()

3. Create a vacuum cleaner agent that cleans a 2D grid automatically.

import random

def print_grid(grid):
for row in grid:
print(" ".join(row))

def vacuum_cleaner(grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "D":
print(f"Cleaning dirt at ({i},{j})")
grid[i][j] = "C"

grid = [[[Link](["C", "D"]) for _ in range(5)] for _ in range(5)]


print("Initial Grid:")
print_grid(grid)

vacuum_cleaner(grid)

print("Final Grid:")
print_grid(grid)

4. Simulate a basic traffic light system using an AI agent that changes lights
based on time.

import time

def traffic_light_system(cycles=3): # Run for 3 cycles


lights = ["Green", "Yellow", "Red"]

3
2025 Introduction to AI using Python

times = [5, 2, 5] # durations in seconds

for _ in range(cycles):
for light, duration in zip(lights, times):
print(f"Traffic Light: {light}")
[Link](duration)

traffic_light_system() # Call runs safely with 3 full cycles

5. Implement Breadth-First Search (BFS) to solve a maze problem.

from collections import deque

def bfs(maze, start, goal):


rows, cols = len(maze), len(maze[0])
queue = deque([start])
visited = set()
parent = {start: None}

while queue:
curr = [Link]()
if curr == goal:
break
for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]:
x, y = curr[0] + dx, curr[1] + dy
if 0 <= x < rows and 0 <= y < cols and maze[x][y] != 1 and (x,y) not in visited:
[Link]((x, y))
[Link]((x, y))
parent[(x, y)] = curr

# Reconstruct path
path = []
step = goal
while step:
[Link](step)
step = [Link](step)
[Link]()
return path

maze = [
[0, 1, 0, 0],
[0, 1, 0, 1],
[0, 0, 0, 0],
[1, 1, 1, 0]
]

start = (0, 0)

4
2025 Introduction to AI using Python

goal = (3, 3)

path = bfs(maze, start, goal)


print("Path:", path)

6. Implement Depth-First Search (DFS) to find a path in a graph.

def dfs(graph, start, visited=None):


if visited is None:
visited = set()
[Link](start)
print(start, end=" ")

for neighbor in graph[start]:


if neighbor not in visited:
dfs(graph, neighbor, visited)

# Sample graph as adjacency list


graph = {
’A’: [’B’, ’C’],
’B’: [’D’, ’E’],
’C’: [’F’],
’D’: [],
’E’: [’F’],
’F’: []
}

print("DFS Traversal:")
dfs(graph, ’A’)

7. Implement Dijkstras Algorithm to find the shortest path in a city map.

import heapq

def dijkstra(graph, start):


heap = [(0, start)]
visited = set()
distances = {node: float(’inf’) for node in graph}
distances[start] = 0

while heap:
cost, node = [Link](heap)
if node in visited:
continue
[Link](node)

5
2025 Introduction to AI using Python

for neighbor, weight in graph[node].items():


if distances[node] + weight < distances[neighbor]:
distances[neighbor] = distances[node] + weight
[Link](heap, (distances[neighbor], neighbor))
return distances

graph = {
’A’: {’B’: 2, ’C’: 4},
’B’: {’C’: 1, ’D’: 7},
’C’: {’E’: 3},
’D’: {’F’: 1},
’E’: {’D’: 2, ’F’: 5},
’F’: {}
}

start = ’A’
print("Shortest distances from A:", dijkstra(graph, start))

8. Solve the 8-puzzle problem using A* Search.

import heapq

goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]

def heuristic(state):
dist = 0
for i in range(3):
for j in range(3):
val = state[i][j]
if val != 0:
goal_x, goal_y = (val - 1) // 3, (val - 1) % 3
dist += abs(i - goal_x) + abs(j - goal_y)
return dist

def get_neighbors(state):
moves = []
x, y = [(ix, iy) for ix, row in enumerate(state) for iy, i in enumerate(row) if i =
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < 3 and 0 <= ny < 3:
new_state = [row[:] for row in state]
new_state[x][y], new_state[nx][ny] = new_state[nx][ny], new_state[x][y]
[Link](new_state)
return moves

def a_star(start):
heap = [(heuristic(start), start)]

6
2025 Introduction to AI using Python

visited = set()
while heap:
h, state = [Link](heap)
if state == goal_state:
print("Goal reached!")
return
[Link](str(state))
for neighbor in get_neighbors(state):
if str(neighbor) not in visited:
[Link](heap, (heuristic(neighbor), neighbor))
print("No solution found.")

start_state = [[1, 2, 3], [4, 0, 6], [7, 5, 8]]


a_star(start_state)

9. Implement a Hill Climbing algorithm to find the highest point in a function.

import random

def objective(x):
return -(x**2) + 10 # Parabola with maximum at x=0

def hill_climb():
current = [Link](-10, 10)
step_size = 0.1
for _ in range(1000):
neighbor = current + [Link](-step_size, step_size)
if objective(neighbor) > objective(current):
current = neighbor
print("Best solution:", round(current, 2), "Value:", round(objective(current), 2))

hill_climb()

10. Simulate Simulated Annealing to solve a simple optimization problem.

import math, random

def objective(x):
return -(x**2) + 10 # Peak at x=0

def simulated_annealing():
current = [Link](-10, 10)
temp = 100.0
cooling = 0.99
while temp > 0.01:
next_guess = current + [Link](-1, 1)

7
2025 Introduction to AI using Python

diff = objective(next_guess) - objective(current)


if diff > 0 or [Link](diff / temp) > [Link]():
current = next_guess
temp *= cooling
print("Best solution:", round(current, 2), "Value:", round(objective(current), 2))

simulated_annealing()

11. Write a Python program to solve a Sudoku puzzle using backtracking.

def is_valid(board, row, col, num):


for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
box_x, box_y = row // 3 * 3, col // 3 * 3
for i in range(box_x, box_x + 3):
for j in range(box_y, box_y + 3):
if board[i][j] == num:
return False
return True

def solve(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
for num in range(1, 10):
if is_valid(board, i, j, num):
board[i][j] = num
if solve(board):
return True
board[i][j] = 0
return False
return True

sudoku = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]

if solve(sudoku):

8
2025 Introduction to AI using Python

for row in sudoku:


print(row)
else:
print("No solution exists.")

12. Implement a graph coloring algorithm to color a simple map.

def is_valid(node, color, assignment, graph):


for neighbor in graph[node]:
if neighbor in assignment and assignment[neighbor] == color:
return False
return True

def color_graph(graph, colors, assignment={}, node=0):


if node == len(graph):
return assignment
for color in colors:
if is_valid(node, color, assignment, graph):
assignment[node] = color
result = color_graph(graph, colors, assignment, node + 1)
if result:
return result
del assignment[node]
return None

graph = {
0: [1, 2],
1: [0, 2, 3],
2: [0, 1],
3: [1]
}
colors = ["Red", "Green", "Blue"]

solution = color_graph(graph, colors)


print("Color Assignment:", solution)

13. Create an AI that plays Rock, Paper, Scissors with random choices.

import random

def play_rps():
choices = ["rock", "paper", "scissors"]
ai_choice = [Link](choices)
user = input("Choose rock, paper or scissors: ").lower()

print("AI chose:", ai_choice)

9
2025 Introduction to AI using Python

if user == ai_choice:
print("It’s a tie!")
elif (user == "rock" and ai_choice == "scissors") or \
(user == "paper" and ai_choice == "rock") or \
(user == "scissors" and ai_choice == "paper"):
print("You win!")
else:
print("AI wins!")

play_rps()

14. Implement the Minimax Algorithm for a simple game like Tic-Tac-Toe.

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

def check_winner(board, player):


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

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

def minimax(board, is_maximizing):


if check_winner(board, "O"):
return 1
if check_winner(board, "X"):
return -1
if is_full(board):
return 0

best = -float(’inf’) if is_maximizing else float(’inf’)


for i in range(3):
for j in range(3):
if board[i][j] == " ":
board[i][j] = "O" if is_maximizing else "X"
score = minimax(board, not is_maximizing)
board[i][j] = " "
best = max(best, score) if is_maximizing else min(best, score)

10
2025 Introduction to AI using Python

return best

def best_move(board):
best_score = -float(’inf’)
move = None
for i in range(3):
for j in range(3):
if board[i][j] == " ":
board[i][j] = "O"
score = minimax(board, False)
board[i][j] = " "
if score > best_score:
best_score = score
move = (i, j)
return move

# Initialize game
board = [[" "]*3 for _ in range(3)]
for _ in range(9):
print_board(board)
x, y = map(int, input("Enter row and column (0-2): ").split())
if board[x][y] != " ":
print("Invalid move")
continue
board[x][y] = "X"
if check_winner(board, "X"):
print("You win!")
break
if is_full(board):
print("Draw")
break
ai_x, ai_y = best_move(board)
board[ai_x][ai_y] = "O"
if check_winner(board, "O"):
print_board(board)
print("AI wins!")
break

11
2025 Introduction to AI using Python

15. Create a rule-based expert system to recommend movies based on user input.

def recommend_movie():
print("Answer yes or no:")
likes_action = input("Do you like action movies? ").lower() == "yes"
likes_romance = input("Do you enjoy romantic movies? ").lower() == "yes"
likes_comedy = input("Do you like comedy? ").lower() == "yes"

if likes_action and not likes_romance:


print("Recommended: Mad Max: Fury Road")
elif likes_romance and not likes_action:
print("Recommended: The Notebook")
elif likes_comedy:
print("Recommended: The Hangover")
else:
print("Recommended: Inception")

recommend_movie()

16. Represent a family tree using Python dictionaries and query relationships.

family = {
"John": {"father": "Robert", "mother": "Linda"},
"Alice": {"father": "John", "mother": "Eva"},
"Bob": {"father": "John", "mother": "Eva"},
"Eva": {"father": "Michael", "mother": "Sarah"}
}

def get_parents(name):
if name in family:
return family[name]["father"], family[name]["mother"]
return None, None

def get_grandparents(name):
father, mother = get_parents(name)
return get_parents(father) + get_parents(mother)

print("Parents of Alice:", get_parents("Alice"))


print("Grandparents of Alice:", get_grandparents("Alice"))

12
2025 Introduction to AI using Python

17. Write a Python program to count the number of words in a given sentence.

def count_words(sentence):
words = [Link]()
return len(words)

sentence = input("Enter a sentence: ")


print("Word count:", count_words(sentence))

18. Create a simple AI that detects positive or negative words in a sentence.

positive_words = ["good", "happy", "love", "excellent", "great"]


negative_words = ["bad", "sad", "hate", "poor", "terrible"]

def detect_sentiment(sentence):
sentence = [Link]()
pos = [word for word in positive_words if word in sentence]
neg = [word for word in negative_words if word in sentence]

if len(pos) > len(neg):


return "Positive Sentiment"
elif len(neg) > len(pos):
return "Negative Sentiment"
else:
return "Neutral Sentiment"

sentence = input("Enter a sentence: ")


print(detect_sentiment(sentence))

19. Implement a basic spam email classifier using if-else conditions.

def is_spam(email_text):
spam_keywords = ["buy now", "free", "click here", "winner", "subscribe"]
text = email_text.lower()
for keyword in spam_keywords:
if keyword in text:
return True
return False

email = input("Enter email content: ")


print("Spam Detected!" if is_spam(email) else "Not Spam.")

13
2025 Introduction to AI using Python

20. Write a Python program to predict the next number in a simple sequence
(e.g., 2, 4, 6, ?).

def predict_next(seq):
if len(seq) < 2:
return "Not enough data"
diff = seq[1] - seq[0]
if all(seq[i+1] - seq[i] == diff for i in range(len(seq)-1)):
return seq[-1] + diff
return "Pattern not recognized"

sequence = list(map(int, input("Enter sequence (comma-separated): ").split(",")))


print("Next number might be:", predict_next(sequence))

21. Build a basic chatbot that responds based on keyword matching.

def keyword_chatbot(user_input):
user_input = user_input.lower()
if "hello" in user_input or "hi" in user_input:
return "Hello! How can I assist you?"
elif "weather" in user_input:
return "It might be sunny or rainy. Check your weather app!"
elif "name" in user_input:
return "I am a keyword-based chatbot."
elif "bye" in user_input:
return "Goodbye!"
else:
return "I’m not sure how to respond to that."

while True:
user_input = input("You: ")
if user_input.lower() == "exit":
break
print("Bot:", keyword_chatbot(user_input))

22. Write a program to classify even and odd numbers using a simple rule-based
AI.

def classify_number(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"

number = int(input("Enter a number: "))

14
2025 Introduction to AI using Python

print("The number is:", classify_number(number))

23. Implement an AI that can detect palindromes in a given string.

def is_palindrome(text):
cleaned = ’’.join(filter([Link], text)).lower()
return cleaned == cleaned[::-1]

text = input("Enter a string: ")


print("Palindrome!" if is_palindrome(text) else "Not a palindrome.")

24. Create a simple weather prediction system using if-else conditions.

def predict_weather(temp, humidity):


if temp > 30 and humidity < 50:
return "Likely to be sunny"
elif humidity > 80:
return "It might rain"
else:
return "Weather is moderate"

temp = int(input("Enter temperature (°C): "))


humidity = int(input("Enter humidity (%): "))
print("Prediction:", predict_weather(temp, humidity))

25. Develop a movie recommendation system using a list of genres and user input.

movies = {
"Action": ["Mad Max", "John Wick"],
"Comedy": ["The Hangover", "Superbad"],
"Romance": ["The Notebook", "Titanic"],
"Horror": ["The Conjuring", "Get Out"]
}

def recommend_movie(genre):
genre = [Link]()
return [Link](genre, ["No recommendations available"])

genre_input = input("Enter a genre (Action, Comedy, Romance, Horror): ")


print("Recommended movies:", recommend_movie(genre_input))

15
2025 Introduction to AI using Python

26. Implement a number guessing game where the AI provides hints.

import random

def number_guessing_game():
number = [Link](1, 100)
attempts = 0
while True:
guess = int(input("Guess the number (1{100): "))
attempts += 1
if guess == number:
print(f"Correct! You guessed it in {attempts} attempts.")
break
elif guess < number:
print("Hint: Try a higher number.")
else:
print("Hint: Try a lower number.")

number_guessing_game()

27. Simulate an AI system that suggests the best route to take based on traffic
conditions.

def suggest_route(traffic):
if traffic == "high":
return "Take the bypass road."
elif traffic == "moderate":
return "Take the main road."
elif traffic == "low":
return "Fastest route is via city center."
else:
return "Invalid traffic input."

traffic = input("Enter traffic condition (high/moderate/low): ").lower()


print("Suggested Route:", suggest_route(traffic))

28. Write a Python program to detect spam words in a text input.

def detect_spam_words(text):
spam_words = ["free", "win", "cash", "buy", "offer", "click"]
found = [word for word in spam_words if word in [Link]()]
return found if found else ["No spam words detected."]

text = input("Enter your message: ")


print("Spam words found:", detect_spam_words(text))

16
2025 Introduction to AI using Python

29. Build a basic text autocorrector using string similarity.

import difflib

def autocorrect(word, word_list):


suggestions = difflib.get_close_matches(word, word_list, n=1, cutoff=0.7)
return suggestions[0] if suggestions else word

dictionary = ["hello", "world", "python", "chatbot", "weather"]


user_input = input("Enter a word: ")
print("Did you mean:", autocorrect(user_input, dictionary))

30. Implement a self-learning agent that improves its guesses over time.

import random

class SelfLearningGuesser:
def __init__(self):
self.guess_range = [1, 100]

def guess(self):
return (self.guess_range[0] + self.guess_range[1]) // 2

def update(self, feedback):


if feedback == "higher":
self.guess_range[0] = self.current_guess + 1
elif feedback == "lower":
self.guess_range[1] = self.current_guess - 1

def play(self, number):


attempts = 0
while True:
self.current_guess = [Link]()
attempts += 1
if self.current_guess == number:
print(f"Guessed correctly: {self.current_guess} in {attempts} attempts.")
break
elif self.current_guess < number:
[Link]("higher")
else:
[Link]("lower")

agent = SelfLearningGuesser()
hidden_number = [Link](1, 100)
[Link](hidden_number)

17
2025 Introduction to AI using Python

18
2025 Introduction to AI using Python

Comprehensive Viva Questions and Answers


1. Q: What is a chatbot?
A: A chatbot is a computer program that simulates human conversation using
predefined responses or AI algorithms.
2. Q: How does a keyword-based chatbot work?
A: It searches for specific keywords in the user input and responds with a predefined
answer mapped to those keywords.
3. Q: What are the limitations of a basic chatbot?
A: It cannot understand context, emotions, or complex queries; it only works on
predefined patterns.
4. Q: How can chatbot intelligence be improved?
A: By using NLP (Natural Language Processing), machine learning, and contextual
memory.
5. Q: What data structure is commonly used in implementing Tic-Tac-Toe?
A: A 2D list or matrix (3x3 grid) is commonly used to represent the game board.
6. Q: What is the role of the Minimax algorithm in games?
A: It helps an AI decide the optimal move by simulating all possible future moves
and choosing the one with the best outcome.
7. Q: Is Rock, Paper, Scissors a deterministic game?
A: No, it is a non-deterministic game when using randomness or human input.
8. Q: Can you make Rock, Paper, Scissors intelligent?
A: Yes, by using pattern learning, frequency analysis, or reinforcement learning.
9. Q: What is an intelligent agent?
A: An intelligent agent is a system that perceives its environment and takes actions
to achieve a goal.
10. Q: How does a vacuum cleaner agent decide what to clean?
A: It senses the grid cell (clean or dirty) and moves accordingly to clean all dirty
cells.
11. Q: What is the environment type of a vacuum cleaner agent?
A: It is a simple, partially observable, and deterministic environment.
12. Q: How can traffic lights be automated using AI?
A: By using timers, sensors, or AI models to control traffic flow based on real-time
data.
13. Q: What is a search algorithm in AI?
A: It is a method used by AI agents to traverse through problem space and find
solutions.
14. Q: What is the difference between BFS and DFS?
A: BFS explores level-by-level using a queue, while DFS explores depth-wise using
a stack or recursion.

19
2025 Introduction to AI using Python

15. Q: Which is better: BFS or DFS?


A: BFS is better for finding the shortest path in unweighted graphs. DFS is more
memory-efficient but may not find the optimal path.
16. Q: What data structures are used in BFS and DFS?
A: BFS uses a queue, DFS uses a stack or recursive function calls.
17. Q: What is Dijkstra’s algorithm used for?
A: It finds the shortest path from a source node to all other nodes in a weighted
graph.
18. Q: What is the time complexity of Dijkstra’s algorithm?
A: O((V + E) log V) when using a priority queue.
19. Q: What is A* (A-Star) search?
A: A* is an informed search algorithm that uses both the actual cost and heuristic
estimate to find the shortest path.
20. Q: What is the formula used in A* search?
A: f(n) = g(n) + h(n), where g is the actual cost and h is the estimated cost to the
goal.
21. Q: What kind of heuristic is used in the 8-puzzle problem?
A: Manhattan distance is commonly used.
22. Q: Can A* guarantee an optimal solution?
A: Yes, if the heuristic is admissible and consistent.
23. Q: What is a heuristic?
A: A heuristic is an educated guess or rule of thumb that helps AI make decisions
faster.
24. Q: What is the Hill Climbing algorithm?
A: It is an iterative algorithm that continuously moves in the direction of increasing
value (uphill) to find the peak.
25. Q: What is the main drawback of Hill Climbing?
A: It can get stuck in local maxima, plateaus, or ridges.
26. Q: What is Simulated Annealing?
A: It is a probabilistic optimization algorithm that accepts worse solutions with a
certain probability to escape local optima.
27. Q: How does temperature affect Simulated Annealing?
A: Higher temperature allows more exploration, lower temperature causes more
exploitation.
28. Q: What is the cooling schedule in Simulated Annealing?
A: It defines how the temperature decreases over time, e.g., T = T * 0.99.
29. Q: Which is better: Hill Climbing or Simulated Annealing?
A: Simulated Annealing is generally better because it avoids getting stuck in local
optima.

20
2025 Introduction to AI using Python

30. Q: What is a Constraint Satisfaction Problem?


A: A problem where a set of variables must be assigned values that satisfy all given
constraints.
31. Q: Give examples of CSPs.
A: Sudoku, Map Coloring, Crossword, N-Queens problem.
32. Q: What algorithm is used to solve Sudoku in AI?
A: Backtracking algorithm (a form of depth-first search).
33. Q: What is backtracking?
A: A trial-and-error method that explores all possible combinations and backtracks
when constraints are violated.
34. Q: How is a Sudoku grid represented in Python?
A: As a 9x9 2D list (matrix) with zeros representing empty cells.
35. Q: What is graph coloring in AI?
A: Assigning colors to graph nodes such that no two adjacent nodes have the same
color.
36. Q: How many colors are required to color any planar map?
A: According to the Four Color Theorem, 4 colors are sufficient.
37. Q: What is the domain in a CSP?
A: The set of possible values that a variable can take.
38. Q: What is adversarial search?
A: A type of search in games where two or more agents compete, like in chess or
tic-tac-toe.
39. Q: What is the Minimax algorithm?
A: An algorithm used in turn-based games to minimize the possible loss while
maximizing potential gain.
40. Q: How does Minimax work?
A: It simulates all possible moves for both players and selects the optimal move
assuming the opponent plays optimally.
41. Q: What is a terminal state in a game?
A: A game state where the game ends — either win, lose, or draw.
42. Q: What is a utility function in game AI?
A: A function that assigns numerical value to the outcome of a game to help decide
optimal moves.
43. Q: Can Rock-Paper-Scissors be solved using Minimax?
A: No, because it’s a non-deterministic game; strategies like probability learning
are used instead.
44. Q: What is the role of a game tree in Minimax?
A: It represents all possible game states and choices for both players.
45. Q: What is knowledge representation in AI?
A: The method of encoding knowledge so that an AI can reason with it (e.g., rules,

21
2025 Introduction to AI using Python

logic, graphs).
46. Q: What is an expert system?
A: A rule-based AI system that mimics human decision-making in specific domains.
47. Q: How is a rule-based system implemented in Python?
A: Using if-else or case-matching statements based on user input.
48. Q: What is a family tree in AI?
A: A representation of relationships using graphs or dictionaries.
49. Q: How are relationships queried in a family tree?
A: By traversing links in dictionaries or graphs.
50. Q: What is NLP in AI?
A: Natural Language Processing enables machines to understand, interpret, and
generate human language.
51. Q: What is tokenization?
A: The process of splitting a sentence into words (tokens).
52. Q: How do you count words in a sentence in Python?
A: Using split() method: len([Link]()).
53. Q: What is sentiment analysis?
A: The process of determining whether a sentence expresses positive, negative, or
neutral emotion.
54. Q: What is a positive/negative word detector?
A: A system that matches words against lists of positive and negative words to
detect sentiment.
55. Q: How does a spam email classifier work?
A: It checks for specific spam keywords like “buy now”, “free”, “click here” in the
message.
56. Q: What is a rule-based AI?
A: An AI that makes decisions using fixed rules (if-else logic).
57. Q: How can AI predict the next number in a sequence?
A: By identifying patterns like arithmetic or geometric progressions.
58. Q: How does an AI detect palindromes?
A: By checking if the string is the same forwards and backwards.
59. Q: What is a self-learning agent?
A: An agent that improves its behavior based on past experience or feedback.
60. Q: How can AI suggest routes based on traffic?
A: Using if-else conditions or real-time traffic data to recommend the best path.
61. Q: What is autocorrection in text?
A: AI compares input word with a dictionary and suggests the closest match using
string similarity.

22
2025 Introduction to AI using Python

Extra Questions
62. Q: How does BFS ensure the shortest path?
A: It visits all nodes at distance d before d+1, so the first time it reaches the goal
is via the shortest path.
63. Q: When is DFS preferred over BFS?
A: DFS is preferred when memory is limited or when searching for any solution is
sufficient (not necessarily shortest).
64. Q: How does the heuristic in A search ensure if it’s admissible?
A: It never overestimates the true cost to the goal, guaranteeing an optimal path.
65. Q: Define “heuristic” in the context of A search.
A: A function that estimates the cost from the current state to the goal, guiding
the search.
66. Q: Why use Manhattan distance for the 8-puzzle?
A: It visits all nodes at distance d before d+1, so the first time it reaches the goal
is via the shortest path.
67. Q: What makes A more efficient than Dijkstra on large graphs?
A: Its heuristic narrows focus to promising paths, reducing the explored nodes.
68. Q: How does Simulated Annealing avoid local optima?
A: By occasionally accepting worse moves with a probability that decreases over
time (”temperature”), allowing escape.
69. Q: What is the “temperature” parameter in Simulated Annealing?
A: A value that controls how likely the algorithm accepts worse solutions; it cools
down as iterations progress.
70. Q: Compare Hill Climbing and Simulated Annealing.
A: Hill Climbing is greedy and faster but risks local optima; Simulated Annealing
is slower but more robust against local traps.
71. Q: How do you choose parameters for Simulated Annealing?
A: Initial temperature, cooling schedule, and termination conditions are chosen
based on experimentation or domain knowledge.
72. Q: What is a fitness function in optimization problems?
A: It evaluates how good a candidate solution is, guiding search algorithms toward
optimal outcomes.

23

You might also like