Cse (Aiml) Artificial Intelligence Lab Manual 22 Scheme
Cse (Aiml) Artificial Intelligence Lab Manual 22 Scheme
LABORATORY MANUAL
ARTIFICIAL INTELLIGENCE LABORATORY/ BAD402
(Effective from the academic year 2023 -2024)
Prepared by
Prof. Vinaya K, Prof. Ambili K, Prof. Kavya P
Assistant Professor’s
Department of CSE-AIML
Compiled by
Dr. Nandeeswar S B
Head of the Department
Department of CSE-AIML
1
Vision and Mission of the
Institution
VISION
“To be leader in Impacting Value Based Technical Education and Research for
the benefit of Society”
MISSION
2
DEPARTMENT OF CSE(AI&ML) ENGINEERING
MD1: To facilitate state of the art infrastructure by providing exposure to the latest AI
MD2: To strive for academic excellence through research in Artificial Intelligence &
MD3: To establish Industry Institute Interaction and make students ready for the
Industrial environment.
3
PROGRAM EDUCATIONAL OBJECTIVES (PEO)
PEO-1: Graduates possess advanced knowledge of Computer Science & Engineering – Artificial
Intelligence & Machine Learning and excel in leadership roles to serve the society.
PEO-2: Graduates of the program will apply Artificial Intelligence enabled Computer Engineering tools
in core technologies for improving knowledge in the Interdisciplinary Research and
Entrepreneurs.
PEO-3: Graduates adapt Value-Based Proficiency in solving Real Time problems.
PSO-1: Professional Skills: Ability of applying the Artificial Intelligence & Machine Learning
knowledge, Computing Concepts, Data Structure, Computer Hardware, Computer Networks and
Suitable Algorithm.
PSO-2: Software Skills: Ability to build Artificial Intelligence enabled Software Engineering System with
Development Life Cycle by using analytical knowledge in Computer Science & Engineering and
applying modern methodologies.
4
PROGRAM OUTCOMES (POs)
PO-1: Engineering knowledge - Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
PO-2: Problem analysis - Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
PO-3: Design/development of solutions - Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
PO-4: Conduct investigations of complex problems - Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO-5: Modern tool usage - Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
PO-6: The engineer and society - Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO-7: Environment and sustainability - Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development
PO-8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO-9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO-10: Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
PO-11: Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
PO-12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
5
lOMoARcPSD|27793530
Sl.NO
Experiments
1 Implement and Demonstrate Depth First Search Algorithm on Water Jug Problem
10 Build a bot which provides all the information related to text in search box
CIE for the theory component of the IPCC (maximum marks 50)
● IPCC means practical portion integrated with the theory of the course.
● CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.
● 25 marks for the theory component are split into 15 marks for two Internal Assessment Tests (Two Tests,
each of 15 Marks with 01-hour duration, are to be conducted) and 10 marks for other assessment methods
mentioned in 22OB4.2. The first test at the end of 40-50% coverage of the syllabus and the second test
after covering 85-90% of the syllabus.
● Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the theory
component of IPCC (that is for 25 marks).
● The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC.
CIE for the practical component of the IPCC
● 15 marks for the conduction of the experiment and preparation of laboratory record, and 10 marks for the
test to be conducted after the completion of all the laboratory sessions.
● On completion of every experiment/program in the laboratory, the students shall be evaluated including
viva-voce and marks shall be awarded on the same day.
● The CIE marks awarded in the case of the Practical component shall be based on the continuous evaluation
of the laboratory report. Each experiment report can be evaluated for 10 marks. Marks of all experiments’
write-ups are added and scaled down to 15 marks.
● The laboratory test (duration 02/03 hours) after completion of all the experiments shall be conducted for
50 marks and scaled down to 10 marks.
● Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory
component of IPCC for 25 marks.
● The student has to secure 40% of 25 marks to qualify in the CIE of the practical component of the IPCC.
SEE for IPCC
Theory SEE will be conducted by University as per the scheduled timetable, with common question papers for
the course (duration 03 hours)
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a maximum
of 3 sub-questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.
4. Marks scoredby the student shall be proportionally scaled down to 50 Marks
The theory portion of the IPCC shall be for both CIE and SEE, whereas the practical portion will have a
CIE component only. Questions mentioned in the SEE paper may include questions from the practical
component.
Suggested Learning Resources:
Text Books
1. Stuart J. Russell and Peter Norvig , Artificial Intelligence, 3rd Edition, Pearson,2015
2. Elaine Rich, Kevin Knight, Artificial Intelligence, 3rd edition,Tata McGraw Hill,2013
Reference:
1. George F Lugar, Artificial Intelligence Structure and strategies for complex, Pearson Education,
5th Edition, 2011
2. Nils J. Nilsson, Principles of Artificial Intelligence, Elsevier, 1980
3. Saroj Kaushik, Artificial Intelligence, Cengage learning, 2014
Web links and Video Lectures (e-Resources)
1. https://www.kdnuggets.com/2019/11/10-free-must-read-books-ai.html
2. https://www.udacity.com/course/knowledge-based-ai-cognitive-systems--ud409
3. https://nptel.ac.in/courses/106/105/106105077/
class WaterJugState:
def __init__(self, jug1, jug2):
self.jug1 = jug1
self.jug2 = jug2
visited.add(current_state)
# Define all possible operations: (action, from_jug, to_jug)
operations = [
('Fill Jug 1', jug1_capacity, current_state.jug2),
('Fill Jug 2', current_state.jug1, jug2_capacity),
('Empty Jug 1', 0, current_state.jug2),
('Empty Jug 2', current_state.jug1, 0),
('Pour Jug 1 to Jug 2',
max(0, current_state.jug1 + current_state.jug2 - jug2_capacity),
min(jug2_capacity, current_state.jug1 + current_state.jug2)),
# Example usage:
jug1_capacity = int(input("Enter Jug 1 capacity : "))
jug2_capacity = int(input("Enter Jug 1 capacity : "))
target_volume = int(input("Enter Target Volume : "))
print(f"Solving Water Jug Problem with capacities ({jug1_capacity}, {jug2_capacity}) to measure
{target_volume} liters.")
solve_water_jug_problem(jug1_capacity, jug2_capacity, target_volume)
OUTPUT
$ p3 01_DFS_WJP.py
Enter Jug 1 capacity : 5
Enter Jug 1 capacity : 4
Enter Target Volume : 3
Solving Water Jug Problem with capacities (5, 4) to measure 3 liters.
Trying: Fill Jug 1 => (5, 0)
Trying: Fill Jug 2 => (5, 4)
Trying: Empty Jug 1 => (0, 4)
Trying: Pour Jug 2 to Jug 1 => (4, 0)
Trying: Fill Jug 2 => (4, 4)
Trying: Pour Jug 2 to Jug 1 => (5, 3)
Jug 2 now has 3 liters.
Solution found!
$ p3 01_DFS_WJP.py
Enter Jug 1 capacity : 2
Enter Jug 1 capacity : 2
Enter Target Volume : 6
Solving Water Jug Problem with capacities (2, 2) to measure 6 liters.
Trying: Fill Jug 1 => (2, 0)
Trying: Fill Jug 2 => (2, 2)
Trying: Empty Jug 1 => (0, 2)
Solution not possible.
lOMoARcPSD|27793530
VIVA QUESTIONS
1. What is the Water Jug Problem?
Answer:
The Water Jug Problem is a classic problem in Artificial Intelligence and Search Algorithms. Given two
jugs of different capacities and an unlimited water supply, the goal is to measure a specific amount of water
using only these jugs and the rules of filling, emptying, and transferring water between them.
9. Can DFS guarantee the shortest solution in the Water Jug Problem?
Answer:
No, DFS does not guarantee the shortest solution because it explores deep paths first without considering
the shortest route. Breadth-First Search (BFS) is better for finding the shortest path.
10. What is the time complexity of DFS for the Water Jug Problem?
Answer:
The time complexity is O(2^n) in the worst case, where n is the number of possible states. However,
pruning using a visited set improves efficiency.
lOMoARcPSD|27793530
def is_valid(self):
# Check if the state is valid (no missionaries eaten on either bank)
if self.left_m < 0 or self.left_c < 0 or self.right_m < 0 or self.right_c < 0:
return False
if self.left_m > 0 and self.left_c > self.left_m:
return False
if self.right_m > 0 and self.right_c > self.right_m:
return False
return True
def is_goal(self):
# Check if the state is the goal state (all missionaries and cannibals on the right bank)
return self.left_m == 0 and self.left_c == 0
def __lt__(self, other):
# Define less-than operator for PriorityQueue comparison (used in Best-First Search)
return False
def __eq__(self, other):
# Define equality operator for comparing states
return self.left_m == other.left_m and self.left_c == other.left_c \
and self.boat == other.boat and self.right_m == other.right_m \
and self.right_c == other.right_c
def __hash__(self):
# Define hash function for storing states in a set
return hash((self.left_m, self.left_c, self.boat, self.right_m, self.right_c))
def successors(state):
# Generate all valid successor states from the current state
succ_states = [ ]
if state.boat == 1: # Boat is on the left bank
for m in range(3):
for c in range(3):
if 1 <= m + c <= 2: # Boat capacity is 2
new_state = State(state.left_m - m, state.left_c - c, 0,
state.right_m + m, state.right_c + c)
if new_state.is_valid( ):
succ_states.append(new_state)
else: # Boat is on the right bank
13
lOMoARcPSD|27793530
for m in range(3):
for c in range(3):
if 1 <= m + c <= 2: # Boat capacity is 2
new_state = State(state.left_m + m, state.left_c + c, 1, state.right_m - m, state.right_c - c)
if new_state.is_valid( ):
succ_states.append(new_state)
return succ_states
def best_first_search( ):
start_state = State(3, 3, 1, 0, 0)
goal_state = State(0, 0, 0, 3, 3)
frontier = PriorityQueue( )
frontier.put((0, start_state)) # Priority queue with (cost, state)
came_from = {}
cost_so_far = {}
came_from[start_state] = None
cost_so_far[start_state] = 0
while not frontier.empty( ):
current_cost, current_state = frontier.get()
if current_state == goal_state:
# Reconstruct the path from start_state to goal_state
path = [ ]
while current_state is not None:
path.append(current_state)
current_state = came_from[current_state]
path.reverse()
return path
for next_state in successors(current_state):
new_cost = cost_so_far[current_state] + 1 # Uniform cost of 1 for each move
if next_state not in cost_so_far or new_cost < cost_so_far[next_state]:
cost_so_far[next_state] = new_cost
priority = new_cost # Best-First Search uses cost as priority
frontier.put((priority, next_state))
came_from[next_state] = current_state
return None # No path found
def print_solution(path):
if path is None:
print("No solution found.")
else:
print("Solution found!")
for i, state in enumerate(path):
print(f"Step {i}:")
print(f"Left Bank: {state.left_m} missionaries, {state.left_c} cannibals")
print(f"Boat is {'on the left' if state.boat == 1 else 'on the right'} bank")
print(f"Right Bank: {state.right_m} missionaries, {state.right_c} cannibals")
print("------------")
# Main function to run the Best-First Search and print the solution
if __name__ == "__main__":
solution_path = best_first_search( )
print_solution(solution_path)
14
lOMoARcPSD|27793530
OUTPUT
Solution found!
Step 0:
Left bank: 3 missionaries, 3 cannibals
Boat is on the left bank
Right bank: 0 missionaries, 0 cannibals
------------
Step 1:
Left bank: 3 missionaries, 1 cannibals
Boat is on the right bank
Right bank: 0 missionaries, 2 cannibals
------------
Step 2:
Left bank: 3 missionaries, 2 cannibals
Boat is on the left bank
Right bank: 0 missionaries, 1 cannibals
Step 3:
Left bank: 3 missionaries, 0 cannibals
Boat is on the right bank
Right bank: 0 missionaries, 3 cannibals
------------
Step 4:
Left bank: 3 missionaries, 1 cannibals
Boat is on the left bank
Right bank: 0 missionaries, 2 cannibals
------------
Step 5:
Left bank: 1 missionaries, 1 cannibals
Boat is on the right bank
Right bank: 2 missionaries, 2 cannibals
------------
15
lOMoARcPSD|27793530
Step 6:
Left bank: 2 missionaries, 2 cannibals
Boat is on the left bank
Right bank: 1 missionaries, 1 cannibals
Step 7:
Left bank: 0 missionaries, 2 cannibals
Boat is on the right bank
Right bank: 3 missionaries, 1 cannibals
------------
Step 8:
Left bank: 0 missionaries, 3 cannibals
Boat is on the left bank
Right bank: 3 missionaries, 0 cannibals
------------
Step 9:
Left bank: 0 missionaries, 1 cannibals
Boat is on the right bank
Right bank: 3 missionaries, 2 cannibals
------------
Step 10:
Left bank: 0 missionaries, 2 cannibals
Boat is on the left bank
Right bank: 3 missionaries, 1 cannibals
------------
Step 11:
Left bank: 0 missionaries, 0 cannibals
Boat is on the right bank
Right bank: 3 missionaries, 3 cannibals
16
lOMoARcPSD|27793530
VIVA QUESTIONS
17
lOMoARcPSD|27793530
import heapq
class Node:
def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
self.state = state # Current state in the search space
self.parent = parent # Parent node
self.action = action # Action that led to this node from the parent node
self.cost = cost # Cost to reach this node from the start node
self.heuristic = heuristic # Heuristic estimate of the cost to reach the goal
18
lOMoARcPSD|27793530
if __name__ == "__main__":
# Get user input to define the graph
print("Define the graph:")
graph = parse_graph_input()
start_state = input("Enter the start state: ")
goal_state = input("Enter the goal state: ")
def goal_test(state):
return state == goal_state
def successors(state):
# Generate successor states from the current state based on the graph
successors_list = [ ]
for neighbor, cost in graph.get(state, [ ]):
action = f"Move to {neighbor}" # Default action (e.g., "Move to B") successor_state = neighbor
step_cost = cost
successors_list.append((action, successor_state, step_cost))
return successors_list
def heuristic(state):
# Define a simple heuristic function (e.g., straight-line distance)
heuristic_values = {key: abs(ord(key) - ord(goal_state)) for key in graph.keys()}
return heuristic_values.get(state, float('inf'))
# Default to infinity if state not found
# Perform A* search using custom successors function
path = astar_search(start_state, goal_test, successors, heuristic)
# Print the resulting path found by A* search
if path:
print("Path found:")
for action, state in path:
print(f"Action: {action}, State: {state}")
else:
print("No path found.")
OUTPUT
$ p3 03Astar_search.py
Define the graph:
Enter the number of edges: 7
Enter an edge (format: u v cost): A B 1
Enter an edge (format: u v cost): A C 3
Enter an edge (format: u v cost): B C 1
Enter an edge (format: u v cost): B D 2
Enter an edge (format: u v cost): C D 1
Enter an edge (format: u v cost): D E 4
Enter an edge (format: u v cost): E G 3
Enter the start state: A
Enter the goal state: G
Path found:
Action: Move to B, State: B
Action: Move to D, State: D
Action: Move to E, State: E
Action: Move to G, State: G
19
lOMoARcPSD|27793530
VIVA QUESTIONS
1. What is the A* Search Algorithm?
Answer: A* is a search algorithm that finds the shortest path from a start node to a goal node. It uses both:
g(n) → The cost from the start node to the current node.
h(n) → A heuristic estimate of the cost from the current node to the goal.
The total cost function is:
f(n)=g(n)+h(n)f(n) = g(n) + h(n)
20
lOMoARcPSD|27793530
21
lOMoARcPSD|27793530
def parse_graph_input():
graph = {}
num_edges = int(input("Enter the number of edges: "))
for _ in range(num_edges):
u, v, cost = input("Enter an edge (format: u v cost): ").split()
cost = float(cost)
if u not in graph:
graph[u] = [ ]
if v not in graph:
graph[v] = [ ]
graph[u].append((v, cost))
return graph
22
lOMoARcPSD|27793530
if path:
print("Path found:")
for action, state in path:
print(f"Action: {action}, State: {state}")
else:
print("No path found.")
OUTPUT
$ p3 04AOstar_search.py
Define the graph:
Enter the number of edges: 8
Enter an edge (format: u v cost): S A 3
Enter an edge (format: u v cost): S B 2
Enter an edge (format: u v cost): A C 4
Enter an edge (format: u v cost): A D 2
Enter an edge (format: u v cost): B E 3
Enter an edge (format: u v cost): C G 2
Enter an edge (format: u v cost): D G 5
Enter an edge (format: u v cost): E G 4
Enter the start state: S
Enter the goal state: G
Path found:
Action: Move to B, State: B
Action: Move to E, State: E
Action: Move to G, State: G
23
lOMoARcPSD|27793530
VIVA QUESTIONS
24
lOMoARcPSD|27793530
25
lOMoARcPSD|27793530
return True
return False
26
lOMoARcPSD|27793530
def print_board(board):
""" Print the board configuration """
n = len(board)
for i in range(n):
for j in range(n):
print(board[i][j], end=" ")
print()
def solve_8queens():
""" Solve the 8-Queens Problem and print the solution """
n = 8 # Size of the chessboard (8x8)
board = [[0] * n for _ in range(n)] # Initialize empty board
if solve_queens(board, 0):
print("Solution found:")
print_board(board)
else:
print("No solution exists.")
OUTPUT
27
lOMoARcPSD|27793530
# Check column
for i in range(row):
if board[i][col] == 1:
return False
return True
# Base case: If all queens are placed, add the solution to the list
if row >= n:
solutions.append([row[:] for row in board])
return
def print_board(board):
""" Print the board configuration """
n = len(board)
for i in range(n):
for j in range(n):
print(board[i][j], end=" ")
print()
28
lOMoARcPSD|27793530
print()
def print_all_solutions():
""" Solve the 8-Queens Problem and print all distinct solutions """
n = 8 # Size of the chessboard (8x8)
board = [[0] * n for _ in range(n)] # Initialize empty board
solutions = []
solve_queens(board, 0, solutions)
29
lOMoARcPSD|27793530
VIVA QUESTIONS
4. How does the backtracking approach work for solving the 8-Queens Problem?
Answer:
Backtracking places queens one by one in each row and backtracks if a conflict is found, trying different placements.
6. What is the heuristic function used in solving the 8-Queens Problem using Hill Climbing?
Answer:
The heuristic function counts the number of attacking pairs of queens and tries to minimize it.
30
lOMoARcPSD|27793530
31
lOMoARcPSD|27793530
import sys
def nearest_neighbor_tsp(distances):
num_cities = len(distances)
current_city = 0
total_distance = 0
# Example usage:
if __name__ == "__main__":
# Example distance matrix (symmetric, square matrix)
# distances = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
distances = [[ 0, 4, 8, 9, 12], [ 4, 0, 6, 8, 9], [ 8, 6, 0, 10, 11], [ 9, 8, 10, 0, 7], [12, 9, 11, 7, 0]]
# Run nearest neighbor TSP algorithm
tour, total_distance = nearest_neighbor_tsp(distances)
32
lOMoARcPSD|27793530
OUTPUT
$ python 06_TSP_heuristics.py
Nearest Neighbor TSP Tour: [0, 1, 2, 3, 4, 0]
Total Distance: 39
VIVA QUESTIONS
33
lOMoARcPSD|27793530
34
lOMoARcPSD|27793530
while new_facts:
new_facts = False
if result == goal:
return True
return False
# Define the rules and facts for the animal classification problem
rules = [
(['hair', 'live young'], 'mammal'),
(['feathers', 'fly'], 'bird')
]
35
lOMoARcPSD|27793530
OUTPUT
$ python 07_Fwd_Bwd_chaining.py
Using forward chaining the cat is classified as a mammal.
Using backward chaining the pigeon is classified as a bird.
36
lOMoARcPSD|27793530
VIVA QUESTIONS
37
lOMoARcPSD|27793530
def negate_literal(literal):
""" Negate a literal by adding or removing the negation symbol '~' """
if literal.startswith('~'):
return literal[1:] # Remove negation
else:
return '~' + literal # Add negation
if resolved:
return new_clause
else:
return None # No resolution possible
while True:
new_clauses = []
n = len(kb)
resolved_pairs = set() # Track resolved pairs to avoid redundant resolutions
for i in range(n):
for j in range(i + 1, n):
clause1 = kb[i]
clause2 = kb[j]
38
lOMoARcPSD|27793530
clause2_tuple = tuple(clause2)
if resolvent is None:
continue # No resolution possible for these clauses
if len(resolvent) == 0:
return True # Empty clause (contradiction), query is proved
# Example usage:
if __name__ == "__main__":
# Example propositional knowledge base (list of clauses)
propositional_kb = [
['~P', 'Q'],
['P', '~Q', 'R'],
['~R', 'S']
]
if result:
print(f"The query '{query}' is PROVED.")
else:
print(f"The query '{query}' is DISPROVED.")
OUTPUT
$ python 08_fopl.py
The query 'S' is DISPROVED.
39
lOMoARcPSD|27793530
VIVA QUESTIONS
1. What is the Resolution Principle in First-Order Predicate Logic (FOPL)?
Answer:
The Resolution Principle is an inference rule used in automated theorem proving. It refutes a given statement by converting it
into clausal form and deriving contradictions using unification and resolution.
40
lOMoARcPSD|27793530
def print_board(board):
""" Print the current state of the Tic-Tac-Toe board """
for row in board:
print(" | ".join(row))
print("-" * 9)
def is_full(board):
""" Check if the board is completely filled """
return all(cell != ' ' for row in board for cell in row)
def tic_tac_toe():
""" Main function to run the Tic-Tac-Toe game """
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X'
while True:
print_board(board)
print(f"Player {current_player}'s turn.")
row = int(input("Enter row (1-3): "))
col = int(input("Enter column (1-3): "))
row -= 1
col -= 1
41
lOMoARcPSD|27793530
if __name__ == "__main__":
tic_tac_toe()
OUTPUT
$ python 09_Tic_Tac_Toe.py
| |
---------
| |
---------
| |
Player X's turn.
Enter row (1-3): 2
Enter column (1-3): 2
| |
---------
| X |
---------
| |
Player O's turn.
Enter row (1-3): 1
Enter column (1-3): 1
O | |
---------
| X |
---------
| |
---------
Player X's turn.
Enter row (1-3): 1
Enter column (1-3): 2
O | X |
---------
| X |
| |
Player O's turn.
Enter row (1-3): 3
Enter column (1-3): 2
O | X |
---------
| X |
---------
| O |
---------
Player X's turn.
Enter row (1-3): 1
Enter column (1-3): 3
O | X | X
42
lOMoARcPSD|27793530
---------
| X |
---------
| O |
Player O's turn.
Enter row (1-3): 3
Enter column (1-3): 3
O | X | X
---------
| X |
---------
| O | O
Player X's turn.
Enter row (1-3): 3
Enter column (1-3): 1
O | X | X
---------
| X |
X | O | O
Player X wins!
43
lOMoARcPSD|27793530
VIVA QUESTIONS
44
lOMoARcPSD|27793530
10. Build a bot which provides all the information related to text in search box
Theory:
The bot performs a Google search based on the user's input and retrieves the search results. You can extend this
code further to include more advanced features such as processing the search results for specific types of
information, implementing natural language processing for understanding user queries better, and integrating
with other APIs for additional functionalities.
To see the results of the above program, you can simply run the script in your Python environment and follow
the instructions. Here's how you can do it:
45
lOMoARcPSD|27793530
Program:
Output:
46
lOMoARcPSD|27793530
import random
class RockPaperScissors:
def init (self):
self.moves = ['rock', 'paper', 'scissors']
self.winning_moves = {'rock': 'scissors', 'paper': 'rock', 'scissors': 'paper'}
def play_round(self, player_move):
computer_move = random.choice(self.moves)
print(f"Computer chooses: {computer_move}")
if player_move == computer_move:
return "It's a tie!"
elif self.winning_moves[player_move] == computer_move:
return "You win!"
else:
return "Computer wins!"
class RandomPlayer:
def init (self):
pass
def get_move(self):
return random.choice(['rock', 'paper', 'scissors'])
class AIPlayer:
def init (self):
pass
def get_move(self, player_moves):
# Basic strategy: Counter the player's last move
last_move = player_moves[-1]
if last_move == 'rock':
lOMoARcPSD|27793530
return 'paper'
elif last_move == 'paper':
return 'scissors'
else:
return 'rock'
# Demonstration
if name == ' main ':
game = RockPaperScissors()
player1 = RandomPlayer()
player2 = AIPlayer()
player_moves = []
for _ in range(3):