0% found this document useful (0 votes)
13 views

800 AI Lab documentation final

This document outlines a comprehensive collection of artificial intelligence lab experiments conducted by Sai Shreya Jillella under the guidance of Dr. Chandrika Dadhirao. It includes various tasks such as programming a vacuum cleaner, solving the Monkey and Banana problem, and the Water Jug problem, demonstrating the application of AI principles and techniques. Each experiment is detailed with objectives, descriptions, and implementation using Python, showcasing the development of intelligent systems and decision-making processes.
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)
13 views

800 AI Lab documentation final

This document outlines a comprehensive collection of artificial intelligence lab experiments conducted by Sai Shreya Jillella under the guidance of Dr. Chandrika Dadhirao. It includes various tasks such as programming a vacuum cleaner, solving the Monkey and Banana problem, and the Water Jug problem, demonstrating the application of AI principles and techniques. Each experiment is detailed with objectives, descriptions, and implementation using Python, showcasing the development of intelligent systems and decision-making processes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

A Comprehensive Collection of Artificial

Intelligence Lab Experiments

A Comprehensive Compilation of Experiments in Artificial Intelligence


(CSEN 2031P)

By : Sai Shreya Jillella( VU22CSEN0100800)

Under the guidance of


Dr. Chandrika Dadhirao

March,2025.

1
Table of Contents
S.no Experiment Date
1 Python & Prolog 20-12-2024
2 Vaccum Cleaner 28-12-2024
3 Monkey Banana 03-01-2025
Problem
4 Water-Jug Problem 14-03-2025

5 8-tiles Problem 30-01-2025

6 Shortest Path Problem 20-02-2025

7 Tic-Tac-Toe game 28-02-2025

8 Hangman Game 17-03-2025

9 Propositional Logic 20-03-2025

10 Inferential Logic 20-03-2025

11 Decision trees 27-03-2025

2
VU22CSEN0100800 WEEK-1 Date: 20-12-2024

Task -1
Date: 20-12-2024

Question: Revisit/Refresh the Study of Python and PROLOG (can


use any other programming Language also).
Aim: The aim of the game, "The Spark of Evolution", is to simulate and
celebrate the journey of human intelligence and innovation. Players
experience pivotal moments in early human history, making choices that
highlight the evolution of reasoning and decision-making, distinguishing
humans from other animals. The game challenges players to solve problems
symbolizing key milestones: mastering fire, creating tools, and inventing the
wheel.
Description : "The Spark of Evolution" is an interactive, decision-based game
that takes players back millions of years to witness and participate in
humanity's evolutionary journey. Starting as a curious ape observing a
burning tree, the player navigates challenges representing humanity's first
sparks of reasoning:
1. Mastering Fire: The player learns how to safely carry fire and understand
its benefits for light, warmth, and protection.
2. Creating Tools: The player discovers how to utilize durable materials like
stone to craft sharp tools, symbolizing a leap in intelligence and
resourcefulness.
3. Inventing the Wheel: The player devises an efficient method to create a
wheel, solving the problem of moving heavy objects, which transforms early
human life. The game underscores the defining traits of human intelligence—
reasoning, decision-making, and innovation—while immersing players in a
rich narrative that combines history and imagination.
By making thoughtful decisions, players progress through milestones that
highlight how curiosity and reasoning shaped the world we know today. This
game bridges storytelling and gameplay, providing both educational and
entertaining insights into the birth of human intelligence.

3
VU22CSEN0100800 WEEK-1 Date: 20-12-2024

The Game Is Implemented Using Google Colabs Language Used : Python

Code:

4
VU22CSEN0100800 WEEK-1 Date: 20-12-2024

5
VU22CSEN0100800 WEEK-1 Date: 20-12-2024

Output:

6
VU22CSEN0100800 WEEK-1 Date: 20-12-2024

1B : Using Prolog
Question: Revisit/Refresh the Study of Python and PROLOG (can
use any other programming Language also).

7
VU22CSEN0100800 WEEK-1 Date: 20-12-2024

8
VU22CSEN0100800 WEEK-2 Date: 28-12-2024

Task-2
Question: Write a program to control the VACUUM Cleaner moves
(Intelligent systems design process).
Aim: The program aims to create an intelligent vacuum cleaner that autonomously
cleans two locations (A and B) using a rule-based system. It evaluates performance by
calculating the cost of cleaning (1 unit per clean) and movement (1 unit per move).
The vacuum decides actions based on the cleanliness of its current location and the
adjacent one. The goal is to ensure both locations are clean while displaying the
cleaning steps, final environment state, and total cost. This simple, rule-based design
promotes efficient decision-making and mimics basic intelligent behavior.
Description: The provided program simulates a simple intelligent agent: a vacuum
cleaner that autonomously cleans two rooms (A and B) based on their cleanliness status.
The vacuum uses a rule-based system to determine its actions, including cleaning the
current location and moving between rooms. The program evaluates its performance by
calculating the total cost of operations, including cleaning and movement.

Key Features:

1. Input Interaction:
○ The user inputs the vacuum's initial location (A or B).
○ The cleanliness status of both the initial room and the other room (0 for
clean, 1 for dirty) is provided.
2. Decision-Making Process:
○ If the current room is dirty, the vacuum cleans it, incurring a cost of 1
unit.
○ If the other room is dirty, the vacuum moves to it, incurring a movement
cost of 1 unit, and cleans it.
3. Performance Evaluation:
○ The program tracks the total cost incurred:
■ Cleaning cost: 1 unit per room cleaned.
■ Movement cost: 1 unit per transition between rooms.
○ The goal is to clean both rooms with minimal cost.
4. Output:
○ The sequence of actions taken by the vacuum cleaner.
○ The final state of both rooms after cleaning.
○ The total cost as a performance metric.

9
VU22CSEN0100800 WEEK-2 Date: 28-12-2024

5. Automation Simulation:
○ The program demonstrates basic automation, mimicking intelligent
decision-making in a controlled, rule-based environment.

CODE:

Language Used : Python

The following code is implemented using Google colabs


def vacuum_world():

# initializing goal_state

# 0 indicates Clean and 1 indicates Dirty

goal_state = {'A': '0', 'B': '0'}

cost = 0

location_input = input("Enter Location of Vacuum") #user_input of location vacuum is


placed

status_input = input("Enter status of " + location_input) #user_input if location is dirty or


clean

status_input_complement = input("Enter status of other room")

print("Initial Location Condition" + str(goal_state))

10
VU22CSEN0100800 WEEK-2 Date: 28-12-2024

if location_input == 'A':

# Location A is Dirty.

print("Vacuum is placed in Location A")

if status_input == '1':

print("Location A is Dirty.")

# suck the dirt and mark it as clean

goal_state['A'] = '0'

cost += 1 #cost for suck

print("Cost for CLEANING A " + str(cost))

print("Location A has been Cleaned.")

if status_input_complement == '1':

# if B is Dirty

print("Location B is Dirty.")

print("Moving right to the Location B. ")

cost += 1 #cost for moving right

print("COST for moving RIGHT" + str(cost))

# suck the dirt and mark it as clean

goal_state['B'] = '0'

cost += 1 #cost for suck

print("COST for SUCK " + str(cost))

print("Location B has been Cleaned. ")

else:

print("No action" + str(cost))

# suck and mark clean

print("Location B is already clean.")

11
VU22CSEN0100800 WEEK-2 Date: 28-12-2024

if status_input == '0':

print("Location A is already clean ")

if status_input_complement == '1':# if B is Dirty

print("Location B is Dirty.")

print("Moving RIGHT to the Location B. ")

cost += 1 #cost for moving right

print("COST for moving RIGHT " + str(cost))

# suck the dirt and mark it as clean

goal_state['B'] = '0'

cost += 1 #cost for suck

print("Cost for SUCK" + str(cost))

print("Location B has been Cleaned. ")

else:

print("No action " + str(cost))

print(cost)

# suck and mark clean

print("Location B is already clean.")

else:

print("Vacuum is placed in location B")

# Location B is Dirty.

if status_input == '1':

print("Location B is Dirty.")

# suck the dirt and mark it as clean

goal_state['B'] = '0'

cost += 1 # cost for suck

12
VU22CSEN0100800 WEEK-2 Date: 28-12-2024

print("COST for CLEANING " + str(cost))

print("Location B has been Cleaned.")

if status_input_complement == '1':

# if A is Dirty

print("Location A is Dirty.")

print("Moving LEFT to the Location A. ")

cost += 1 # cost for moving right

print("COST for moving LEFT" + str(cost))

# suck the dirt and mark it as clean

goal_state['A'] = '0'

cost += 1 # cost for suck

print("COST for SUCK " + str(cost))

print("Location A has been Cleaned.")

else:

print(cost)

# suck and mark clean

print("Location B is already clean.")

if status_input_complement == '1': # if A is Dirty

print("Location A is Dirty.")

print("Moving LEFT to the Location A. ")

cost += 1 # cost for moving right

print("COST for moving LEFT " + str(cost))

# suck the dirt and mark it as clean

goal_state['A'] = '0'

cost += 1 # cost for suck

13
VU22CSEN0100800 WEEK-2 Date: 28-12-2024

print("Cost for SUCK " + str(cost))

print("Location A has been Cleaned. ")

else:

print("No action " + str(cost))

# suck and mark clean

print("Location A is already clean.")

# done cleaning

print("GOAL STATE: ")

print(goal_state)

print("Performance Measurement: " + str(cost))

vacuum_world()

SAMPLE OUTPUT:
Enter Location of Vacuum: A

Enter status of: A1

Enter status of other room1

Initial Location Condition{'A': '0', 'B': '0'}

Vacuum is placed in Location A

Location A is Dirty.

Cost for CLEANING A 1

Location A has been Cleaned.

Location B is Dirty.

Moving right to the Location B.

COST for moving RIGHT2

COST for SUCK 3

Location B has been Cleaned.

14
VU22CSEN0100800 WEEK-2 Date: 28-12-2024

GOAL STATE:

{'A': '0', 'B': '0'}

Performance Measurement: 3

15
VU22CSEN0100800 WEEK-3 Date: 03-01-2025

Task-3
Question: Write a program to solve Monkey & Banana Problem.
Aim: To implement a solution for the Monkey and Banana Problem using
Python, where the monkey must reach the banana by performing a sequence
of actions. The problem is solved using state-space search, demonstrating
how an agent (monkey) makes decisions to achieve a goal.
Description: The Monkey and Banana Problem is a classic AI planning
problem where a monkey must retrieve a banana that is hanging from the
ceiling. The challenge is that the monkey cannot reach the banana directly; it
must use a box to climb and grab the banana. This problem demonstrates
state-space search, goal-oriented behavior, and decision-making in AI.
Code:

16
VU22CSEN0100800 WEEK-3 Date: 03-01-2025

Output:

17
VU22CSEN0100800 WEEK-4 Date: 14-02-2025

Task-4
Question: You have three jugs with capacities of 8 liters, 5 liters, and 3 liters. The 8-
liter jug is full, and the other two are empty. How can you measure exactly 4 liters in
one of the jugs?
With jug capacities of 10 liters, 7 liters, and 4 liters, how can you get exactly 2 liters in
one of the jugs?
Aim: The Water Jug Problem aims to demonstrate and apply state-space search
techniques to solve a real-world-inspired problem using Artificial Intelligence (AI)
principles. Specifically, the objective is to find the shortest sequence of steps that leads
to a desired goal state, such as measuring an exact quantity of water using two or more
jugs of predefined capacities.
Description: The Water Jug Problem involves measuring a specific amount of water
using two jugs with predefined capacities. The problem is approached algorithmically
by modelling possible states of the jugs and using BFS to find the shortest sequence of
actions leading to the desired amount of water.

The program achieves the following:

1. Solve the Problem Using BFS:


○ Represents the jugs' states as tuples (x, y), where x is the water level in Jug
1, and y is the water level in Jug 2.
○ Considers all possible actions:
■ Filling a jug.
■ Emptying a jug.
■ Pouring water between jugs.
2. Visualize the Process:
○ Uses Pygame to graphically represent the water levels in the jugs as they
change over time.
○ Provides a clear and interactive visualization of the solution.
3. Implementation Details:
○ BFS ensures that the solution is the shortest path to the goal state.
○ Actions and transitions are animated for better understanding.

Code:

Language Used : Python

18
VU22CSEN0100800 WEEK-4 Date: 14-02-2025

The following code is implemented using Visual Studio Code

import pygame

from collections import deque

import time

# Initialize Pygame

pygame.init()

# Screen dimensions and colors

WIDTH, HEIGHT = 600, 400

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

BLUE = (0, 0, 255)

# Set up display

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Water Jug Problem Visualization")

# Font for rendering text

font = pygame.font.Font(None, 30)

# Jug dimensions for visualization

jug_positions = [(100, 200), (250, 200), (400, 200)] # x, y positions

jug_width, jug_height = 50, 150

def draw_jugs(state, capacities):

"""Draw the jugs with the current state."""

screen.fill(WHITE)

for i, (x, y) in enumerate(jug_positions):

# Draw the jug

19
VU22CSEN0100800 WEEK-4 Date: 14-02-2025

pygame.draw.rect(screen, BLACK, (x, y - jug_height, jug_width, jug_height), 2)

# Draw the water level

water_height = (state[i] / capacities[i]) * jug_height if capacities[i] > 0 else 0

pygame.draw.rect(screen, BLUE, (x, y - water_height, jug_width, water_height))

# Display the current amount

text = font.render(f"{state[i]}L", True, BLACK)

screen.blit(text, (x + 5, y + 10))

pygame.display.flip()

def solve_water_jug_problem_visual(capacities, goal):

"""Solve the water jug problem with visualization."""

cap_a, cap_b, cap_c = capacities

initial_state = (cap_a, 0, 0)

queue = deque([initial_state])

visited = set()

visited.add(initial_state)

def pour(source, dest, cap_dest):

pour_amount = min(source, cap_dest - dest)

return source - pour_amount, dest + pour_amount

while queue:

state = queue.popleft()

draw_jugs(state, capacities) # Visualize the state

time.sleep(1) # Pause to visualize steps

if goal in state:

return state

20
VU22CSEN0100800 WEEK-4 Date: 14-02-2025

next_states = [

(*pour(state[0], state[1], cap_b), state[2]), # Pour A -> B

(*pour(state[0], state[2], cap_c), state[1]), # Pour A -> C

(pour(state[1], state[0], cap_a)[1], *pour(state[1], state[2], cap_c)), # Pour B ->


C

(pour(state[2], state[0], cap_a)[1], state[1], *pour(state[2], state[1], cap_b)), #


Pour C -> B

for new_state in next_states:

if new_state not in visited:

visited.add(new_state)

queue.append(new_state)

return None # No solution found

def main():

"""Main function to run the visualization."""

capacities = (8, 5, 3) # Change to (10, 7, 4) for the second problem

goal = 4 # Change to 2 for the second problem

running = True

solution = None

while running:

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

if not solution:

solution = solve_water_jug_problem_visual(capacities, goal)


21
VU22CSEN0100800 WEEK-4 Date: 14-02-2025

# Wait to display the final state after solving

time.sleep(3)

running = False

pygame.quit()

if solution:

print("Solution:", solution)

else:

print("No solution found.")

if __name__ == "__main__":

main()

OUTPUT:

22
VU22CSEN0100800 WEEK-5 Date: 21-02-2025

Task-5a

Aim: To solve the 8 Puzzle Problem using an algorithmic approach, demonstrating


manual solving techniques and a programmatic solution using state-space search
strategies like Breadth-First Search (BFS), Depth-First Search (DFS), or A Search*.

Description:The 8 Puzzle Problem consists of a 3x3 grid containing 8 numbered tiles


(1-8) and one blank space. The objective is to rearrange the tiles from an initial
configuration to a goal configuration by sliding tiles into the blank space.

Goal State Example:

123

456

78

Initial State Example:

123

4 6

758

1. Write a program to solve Shortest path problem: (ii) Using Lowest-


cost-first search

23
VU22CSEN0100800 WEEK-5 Date: 21-02-2025

PYTHON CODE :

import heapq
def lowest_cost_first_search(graph, start, goal):
"""
Solves the shortest path problem using Lowest-Cost-First Search.
:param graph: Dictionary representing the graph as {node: [(neighbor, cost),
...]}.
:param start: Starting node.
:param goal: Goal node.
:return: Tuple of (shortest path, cost) or (None, float('inf')) if no path exists.
"""
# Priority queue to store (cost, current_node, path)
priority_queue = [(0, start, [start])]
visited = set() # To keep track of visited nodes

24
VU22CSEN0100800 WEEK-5 Date: 21-02-2025

while priority_queue:
current_cost, current_node, path = heapq.heappop(priority_queue)
# Skip already visited nodes
if current_node in visited:
continue
visited.add(current_node)
# Goal reached
if current_node == goal:
return path, current_cost
# Explore neighbors
for neighbor, cost in graph.get(current_node, []):
if neighbor not in visited:
heapq.heappush(priority_queue, (current_cost + cost, neighbor, path +
[neighbor]))
# If no path found
return None, float('inf')
# Graph from the image as adjacency list
graph = {
'C': [('B', 2), ('T', 1), ('O', 3), ('E', 2), ('P', 5)],
'B': [('A', 1), ('R', 4), ('S', 3)],
'O': [('I', 1), ('N', 2)],
'E': [('G', 5)],
'P': [('L', 5), ('F', 1), ('D', 3)],
'I': [('Z', 2)],
'A': [], 'R': [], 'S': [], 'N': [], 'G': [], 'L': [], 'F': [], 'D': [], 'Z': []
}

25
VU22CSEN0100800 WEEK-5 Date: 21-02-2025

# Define start and goal nodes


start_node = 'C'
goal_node = 'Z'
# Find shortest path
path, cost = lowest_cost_first_search(graph, start_node, goal_node)
# Display results
if path:
print(f"Shortest path: {' -> '.join(path)} with cost: {cost}")
else:
print(f"No path exists between {start_node} and {goal_node}")

OUTPUT :

Shortest path: C -> O -> I -> Z with cost: 6

2. Write a program to solve Shortest path problem Using BFS

26
VU22CSEN0100800 WEEK-5 Date: 21-02-2025

PYTHON CODE :

from collections import deque

# BFS function to find the shortest path

def bfs_shortest_path(graph, start, goal):

# Queue for BFS: stores (current_node, path_to_current_node)

queue = deque([(start, [start])])

visited = set() # Keep track of visited nodes

while queue:

current_node, path = queue.popleft()

# If the goal is found, return the path

if current_node == goal:

return path

# Mark the node as visited

visited.add(current_node)

# Add neighbors to the queue if not visited

for neighbor in graph[current_node]:

if neighbor not in visited:

queue.append((neighbor, path + [neighbor]))

# If the goal is not reachable, return None

return None

# Define the tree as an adjacency list based on the uploaded image

tree = {

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

27
VU22CSEN0100800 WEEK-5 Date: 21-02-2025

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

'C': ['D', 'G'],

'D': ['C', 'F', 'G'],

'E': [],

'F': ['G', 'H'],

'G': [],

'H': []

# Test the BFS function

start_node = 'A'

goal_node = 'H'

shortest_path = bfs_shortest_path(tree, start_node, goal_node)

if shortest_path:

print(f"Shortest path from {start_node} to {goal_node}:


{shortest_path}")

else:

print(f"No path exists from {start_node} to {goal_node}")

OUTPUT :

Shortest path from A to H: ['A', 'B', 'D', 'F', 'H']

3. 8 Puzzle problem

28
VU22CSEN0100800 WEEK-6 Date: 28-02-2025

Task-6
Date: 20-02-2025
Question: Write a program to solve shortest path problem: (i) Using BFS (ii) Using
Lowest-cost-first search.
Aim: The aim is to implement algorithms for finding the shortest path in a graph using
BFS and to create an AI for playing Tic-Tac-Toe using the minimax algorithm with
alpha-beta pruning.
Description: This part of the code implements the Breadth-First Search (BFS)
algorithm to find the shortest path between two nodes in an unweighted graph. The
graph is represented as an adjacency list, where each node is associated with a list of its
neighboring nodes. The bfs_shortest_path(graph, start, goal) function starts by adding
the start node to a queue and iteratively explores all possible paths from the start node.
It checks each node level by level and ensures that the shortest path (in terms of the
number of edges) is found. Once the goal node is reached, the function returns the path
from the start to the goal. If no path exists, it returns None. The algorithm ensures an
optimal solution for finding the shortest path in unweighted graphs.

Part(i):
from collections import deque

# BFS algorithm to find the shortest path


def bfs_shortest_path(graph, start, goal):
queue = deque([[start]]) # Queue to hold paths
visited = set() # Set to track visited nodes

if start == goal:
return [start] # If start and goal are the same, return the path containing just the start

while queue:
path = queue.popleft() # Get the current path from the queue
node = path[-1] # The current node is the last element in the path

49
VU22CSEN0100800 WEEK-6 Date: 28-02-2025

if node not in visited:


neighbors = graph[node] # Get the neighbors of the current node

for neighbor in neighbors:


new_path = list(path) # Create a new path with the current node and neighbor
new_path.append(neighbor)
queue.append(new_path) # Add the new path to the queue

if neighbor == goal:
return new_path # Return the path if the goal is found
visited.add(node) # Mark the node as visited

return None # If no path is found

# Input graph from the user


graph = {}
n = int(input("Enter number of nodes: "))
for _ in range(n):
node = input("Enter node: ")
neighbors = input(f"Enter neighbors of {node} (comma separated): ").split(',')
graph[node] = [neighbor.strip() for neighbor in neighbors]

start = input("Enter start node: ")


goal = input("Enter goal node: ")

# Find the shortest path using BFS


path = bfs_shortest_path(graph, start, goal)

# Output the result


if path:
print(f"Shortest path from {start} to {goal}: {' -> '.join(path)}")
else:

50
VU22CSEN0100800 WEEK-6 Date: 28-02-2025

print("No path found.")

Output

Part(ii):
Code:
import heapq

# Function to perform Dijkstra's algorithm

def dijkstra(graph, start, goal):

# Min-heap priority queue for processing nodes with the smallest distance

queue = [(0, start)] # (distance, node)

distances = {start: 0} # Dictionary to store the shortest distance to each node

previous_nodes = {start: None} # To track the path

while queue:

current_distance, current_node = heapq.heappop(queue)

# If we reach the goal, reconstruct the path

if current_node == goal:

51
VU22CSEN0100800 WEEK-6 Date: 28-02-2025

path = []

while current_node is not None:

path.append(current_node)

current_node = previous_nodes[current_node]

return path[::-1] # Reverse the path to get the correct order

# If a shorter path to the current node is found, skip processing

if current_distance > distances.get(current_node, float('inf')):

continue

# Explore neighbors

for neighbor, weight in graph[current_node]:

distance = current_distance + weight

# If a shorter path to the neighbor is found, update the data structures

if distance < distances.get(neighbor, float('inf')):

distances[neighbor] = distance

previous_nodes[neighbor] = current_node

heapq.heappush(queue, (distance, neighbor))

return None # If no path is found

# Input graph from user in the form of an adjacency list with weights

graph = {}

n = int(input("Enter number of nodes: "))

for _ in range(n):

node = input("Enter node: ")

neighbors = input(f"Enter neighbors and weights of {node} (format: neighbor1:weight, neighbor2:weight): ").split(',')

graph[node] = []

for neighbor in neighbors:

neighbor_name, weight = neighbor.split(':')

graph[node].append((neighbor_name.strip(), int(weight)))

start = input("Enter start node: ")

goal = input("Enter goal node: ")

52
VU22CSEN0100800 WEEK-6 Date: 28-02-2025

# Find the shortest path using Dijkstra's algorithm

path = dijkstra(graph, start, goal)

# Output the result

if path:

print(f"Shortest path from {start} to {goal}: {' -> '.join(path)}")

else:

print("No path found.")

Output:

53
VU22CSEN0100800 WEEK-7 Date: 02-03-2025

Task-7

Question: Write a program to implement TIC – TAC - TOE game (Understanding


Minimax Algorithm and Alpha – Beta pruning).
Aim: The objective of Tic-Tac-Toe is to be the first player to get three of your
marks (either X or O) in a row, column, or diagonal on a 3x3 grid. Players take
turns marking a spot on the grid, and the game ends when either a player wins or
the grid is completely filled, resulting in a draw if no winner is determined.

Description: The Tic-Tac-Toe game, commonly played on a 3x3 grid, has the objective of getting
three of the same marks (either 'X' or 'O') in a row, column, or diagonal. Players take turns marking
empty spaces on the grid, and the first to align three marks wins the game. If all spaces are filled and
no player wins, the game results in a draw.
Step-by-Step Explanation:
1. Initialize Pygame: Set up the window and basic configurations.
2. Draw the grid: Use Pygame's drawing functions to draw the Tic-Tac-Toe grid.
3. Player input: Handle player clicks to place X's and O's on the grid.
4. Win conditions: Check for horizontal, vertical, or diagonal lines that match.

Code :

54
VU22CSEN0100800 WEEK-7 Date: 02-03-2025

Output:

55
VU22CSEN0100800 WEEK-8 Date: 17-03-2025

Task-8
Date: 17-03-2025
Question: Write a program to implement Hangman game (Or Wordle).
Aim: The aim of Hangman is to correctly guess the hidden word by selecting letters
within a limited number of attempts while avoiding too many incorrect guesses. Players
must use their vocabulary, spelling skills, and logical reasoning to figure out the word
before the hangman figure is completely drawn. Each incorrect guess results in a part of
the figure being added, bringing the player closer to losing the game. The challenge lies
in making strategic guesses, starting with common letters and using clues from
previously revealed letters to deduce the correct word before running out of chances.
Description: Hangman is a word-guessing game where a player attempts to uncover a hidden word
by guessing letters within a limited number of chances. The game typically begins with a blank
representation of the word, with each blank corresponding to a letter in the word. Players take turns
guessing letters, and if a guessed letter is in the word, it is revealed in its correct position. However, if
the guessed letter is incorrect, a part of a stick figure—representing the "hangman"—is drawn. The
game continues until the player either correctly identifies the word or exhausts all allowed incorrect
guesses, leading to a loss. This game is both educational and entertaining, helping players improve
their vocabulary, spelling, and logical thinking skills. Hangman is often played in classrooms, as a
casual pastime, or even in digital formats, making it widely accessible. Variations of the game include
themed versions where words belong to specific categories, such as movies, animals, or history. It can
be played by two or more players, with one person selecting the word while the others attempt to guess
it. The simplicity of the game, combined with the challenge of guessing words strategically, makes
Hangman a timeless and engaging activity for all ages.

Code:

56
VU22CSEN0100800 WEEK-8 Date: 17-03-2025

57
VU22CSEN0100800 WEEK-8 Date: 17-03-2025

58
VU22CSEN0100800 WEEK-8 Date: 17-03-2025

Output:

59
VU22CSEN0100800 WEEK-8 Date: 17-03-2025

60
VU22CSEN0100800 WEEK-9 Date: 20-03-2025

Task-9
Date: 20-03-2025
Question: Write a program to understand Propositional logic using
KANREN, SYMPY, pyDatalog packages in Python.
Aim: The aim is to implement and explore Propositional Logic using the Python
libraries KANREN, SYMPY, and pyDatalog. The program will demonstrate how to
represent and solve logical expressions, such as logical propositions, using these
libraries. It will also provide an understanding of how these libraries support logical
reasoning and constraint satisfaction problems.
Description: This program explores Propositional Logic using three different Python
libraries: KANREN, SYMPY, and pyDatalog, each offering unique approaches for
logical reasoning and constraint satisfaction. KANREN is a logic programming library
that allows the representation of logical relationships through relational programming,
enabling the definition of logical variables and querying of satisfiable conditions.
SYMPY, a symbolic mathematics library, provides tools to represent and manipulate
logical expressions symbolically, allowing for simplification and evaluation of
propositional logic formulas. pyDatalog extends the concept of logic programming by
allowing logical rules and queries to be expressed and evaluated using Datalog, a
declarative query language.
Code:
from kanren import run, var, fact, Relation
from sympy import symbols, Or, And, Not, Implies, Equivalent
from pyDatalog import pyDatalog
# ===================== Using Kanren =====================
parent = Relation('parent')
wears = Relation('wears')
brother = Relation('brother')
# Facts from the image (John the king wears the crown, John has a brother)
fact(wears, 'John', 'crown')
fact(brother, 'John', 'L')
x = var()
print("Using kanren:")

61
VU22CSEN0100800 WEEK-9 Date: 20-03-2025

print("Who wears the crown?", run(1, x, wears(x, 'crown')))


print("Who is John's brother?", run(1, x, brother('John', x))
A, B, C = symbols('A B C')
expr1 = And(A, Or(B, Not(C)))
expr2 = Implies(A, B)
expr3 = Equivalent(A, Not(B))
print("\nUsing sympy:")
print("Expression 1 (A AND (B OR NOT C)):", expr1)
print("Expression 2 (A -> B):", expr2)
print("Expression 3 (A <-> NOT B):", expr3)
# Example: Proof by resolution using FOL
American, Weapon, Missile, Enemy, Sells, Hostile, Criminal, West, Nono = symbols(
'American Weapon Missile Enemy Sells Hostile Criminal West Nono')
law = Implies(And(American, Sells, Hostile), Criminal)
nono_enemy = Equivalent(Nono, Enemy)
west_sells = Implies(West, Sells)
enemy_hostile = Implies(Enemy, Hostile)
proof = And(law, nono_enemy, west_sells, enemy_hostile)
print("\nProof by resolution:")
print("Is West a criminal?", proof.simplify())
# ===================== Using PyDatalog =====================
pyDatalog.clear()
pyDatalog.create_terms('X, Y, Z, parent, grandparent, wears, brother')
parent['Alice'] = 'Bob'
parent['Bob'] = 'Charlie'
wears['John'] = 'crown'
brother['John'] = 'L'
grandparent[X] = parent[X] & parent[Y]
print("\nUsing pyDatalog:")
print("Grandparent relationships:", grandparent[X] == Y)
print("Who wears the crown?", wears[X] == 'crown')
print("Who is John's brother?", brother['John'] == Y)

62
VU22CSEN0100800 WEEK-9 Date: 20-03-2025

Output:

63
VU22CSEN0100800 WEEK-10 Date: 20-03-2025

Task -10

Question: Write a program to understand Inferential logic using KANREN, SYMPY,


pyDatalog packages in Python.THE EXAMPLES COVERED IN CLASS SHOULD
BE CONSIDERED AS PROGRAM OUTPUT.
Aim: The aim is to implement and understand Inferential Logic using the Python
libraries KANREN, SYMPY, and pyDatalog. The program will demonstrate how these
libraries can be used to infer logical conclusions based on a set of premises, focusing
on reasoning and deduction.
Description: This program demonstrates Inferential Logic using three Python libraries:
KANREN, SYMPY, and pyDatalog. Each library offers a different approach to logical
reasoning. KANREN allows reasoning through relational programming by inferring
relationships and solving for unknowns. SYMPY simplifies logical expressions and
performs deductions using symbolic logic. pyDatalog utilizes logic programming to
define relationships and infer new facts. The program showcases how to infer
conclusions, simplify expressions, and deduce new facts from given premises using
these libraries.
Code:
from kanren import run, var, fact, Relation
from sympy import symbols, Or, And, Not, Implies, Equivalent
from pyDatalog import pyDatalog

# ===================== Using Kanren (Inferential Logic)


=====================
# Defining Relations
wears = Relation('wears')
king = Relation('king')
rule = Relation('rule')

# Facts from the image (John the king wears the crown)

64
VU22CSEN0100800 WEEK-10 Date: 20-03-2025

fact(king, 'John')
fact(wears, 'John', 'crown')
fact(rule, 'John')

x = var()
print("Using kanren (Inferential Logic):")
print("Who wears the crown?", run(1, x, wears(x, 'crown')))
print("Who is the king?", run(1, x, king(x)))
print("Who rules the kingdom?", run(1, x, rule(x)))

# ===================== Using SymPy (Inferential Logic)


=====================
A, B, C = symbols('A B C')
expr1 = Implies(A, B)
expr2 = Equivalent(A, Not(C))
expr3 = And(A, Or(B, Not(C)))

print("\nUsing sympy:")
print("Expression 1 (A -> B):", expr1)
print("Expression 2 (A <-> NOT C):", expr2)
print("Expression 3 (A AND (B OR NOT C)):", expr3)

# Example: Proof by resolution using FOL


American = symbols('American')
Weapon = symbols('Weapon')
Missile = symbols('Missile')
Enemy = symbols('Enemy')
Sells = symbols('Sells')
65
VU22CSEN0100800 WEEK-10 Date: 20-03-2025

Hostile = symbols('Hostile')
Criminal = symbols('Criminal')
West = symbols('West')
Nono = symbols('Nono')

law = Implies(And(American, Sells, Hostile), Criminal)


nono_enemy = Equivalent(Nono, Enemy)
west_sells = Implies(West, Sells)
enemy_hostile = Implies(Enemy, Hostile)

proof = And(law, nono_enemy, west_sells, enemy_hostile)


print("\nProof by resolution:")
print("Is West a criminal?", proof.simplify())

# ===================== Using PyDatalog (Inferential Logic)


=====================
pyDatalog.clear()
pyDatalog.create_terms('X, Y, Z, king, wears, ruler')
king['John'] = True
wears['John'] = 'crown'
ruler[X] = king[X]

print("\nUsing pyDatalog:")
print("Who is the king?", king[X] == True)
print("Who wears the crown?", wears[X] == 'crown')
print("Who rules?", ruler[X] == True)

66
VU22CSEN0100800 WEEK-10 Date: 20-03-2025

Output:

67
VU22CSEN0100800 WEEK-11 Date: 27-03-2025

Task-11

Question: Write a program to implement a binary classification using Decision Trees


(Understanding Decision Trees).
Aim: To implement a decision tree classifier on a dataset of Formula 1 drivers, calculate
entropy and information gain to evaluate the effectiveness of each feature in
classification, and visualize the resulting decision tree to analyze the decision-making
process.
Description: This project aims to build and analyze a decision tree classifier using a
dataset that records the performance of Formula 1 drivers based on various a ributes.
The dataset includes informa on such as the driver's team, type of track, weather
condi ons, and finishing posi on, with the target variable being the outcome (win or
loss).
The decision tree algorithm will use entropy as the criterion to calculate information
gain at each node, helping identify the most significant features that contribute to
predicting the outcome. The trained decision tree will then be visualized using
matplotlib to provide a clear and intuitive understanding of the classification process.
Additionally, the project evaluates how well the model performs in classifying outcomes
and highlights key decision points that influence the results.

68
VU22CSEN0100800 WEEK-11 Date: 27-03-2025

Code:
# Import necessary libraries

import pandas as pd

from sklearn.tree import DecisionTreeClassifier

from sklearn.preprocessing import LabelEncoder

from sklearn import tree

import matplotlib.pyplot as plt

# Dataset

data = {

'Driver': ['Verstappen', 'Hamilton', 'Leclerc', 'Norris', 'Sainz', 'Russell', 'Alonso'],

'Team': ['Red Bull', 'Mercedes', 'Ferrari', 'McLaren', 'Ferrari', 'Mercedes', 'Aston Martin'],

'Track_type': ['Street', 'Circuit', 'Street', 'Circuit', 'Circuit', 'Street', 'Circuit'],

'Weather': ['Dry', 'Wet', 'Dry', 'Dry', 'Wet', 'Wet', 'Dry'],

'Position': [1, 2, 3, 2, 4, 3, 5],

'Outcome': ['Win', 'Loss', 'Loss', 'Win', 'Loss', 'Loss', 'Win']

# Create DataFrame

df = pd.DataFrame(data)

# Encode categorical variables

label_encoder = LabelEncoder()

for col in ['Team', 'Track_type', 'Weather', 'Outcome']:

df[col] = label_encoder.fit_transform(df[col])

# Define features and target variable

X = df[['Team', 'Track_type', 'Weather', 'Position']]

y = df['Outcome']

# Create and train the Decision Tree model

model = DecisionTreeClassifier(criterion='entropy', max_depth=3)

model.fit(X, y)

# Plot the decision tree with spacier layout and colors

plt.figure(figsize=(14, 10))

tree.plot_tree(

model,

69
VU22CSEN0100800 WEEK-11 Date: 27-03-2025

feature_names=['Team', 'Track_type', 'Weather', 'Position'],

class_names=['Loss', 'Win'],

filled=True,

rounded=True,

fontsize=10,

impurity=True,

node_ids=True,

proportion=False,

# Set colors manually for Win and Loss

ax = plt.gca()

for i, node in enumerate(ax.findobj(plt.Text)):

if "Loss" in node.get_text():

node.set_color('red')

elif "Win" in node.get_text():

node.set_color('blue')

# Show the decision tree

plt.tight_layout()

plt.show()

Output:

The end

70

You might also like