AI - File Copy 2
AI - File Copy 2
A023167022058 1-Y
Experiment 1
Program 1-
def astaralgo(start_node, stop_node): open_set = set([start_node])
# Open set contains the starting node closed_set = set() # Closed
set to store visited nodes
g[start_node] = 0
parents[start_node] = start_node
if n is None:
print("Path does not exist!")
return None
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
print("Path found:
{}".format(path))
return path
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,
}
return H_dist.get(n, float('inf')) # Default to infinity if node is not found
Graph_nodes = {
'A': [('B', 2), ('E', 3)],
'B': [('C', 1), ('G', 9)],
'C': [],
'E': [('D', 6)],
'D': [('G', 1)],
}
astaralgo('A', 'G')
Output-
Program2:
heapq
ROW = 9
COL = 10
self.parent_i = -1 self.parent_j = -1
return grid[row][col] == 1
cell_details[row][col].parent_i temp_col =
temp_row, temp_col
path.append((row, col))
path.reverse()
for i in path:
print()
return
Shreya Sankhwar
A023167022058 1-Y
i, j = src cell_details[i]
[j].f = 0 cell_details[i][j].g
=0 cell_details[i][j].h = 0
cell_details[i][j].parent_i = i
cell_details[i][j].parent_j = j
open_list = []
found_dest = False
# A* Algorithm loop
p = heapq.heappop(open_list)
i, j = p[1], p[2]
closed_list[i][j] = True
(1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
cell_details[new_i][new_j].parent_i = i
cell_details[new_i][new_j].parent_j = j print("The
g_new + h_new
cell_details[new_i][new_j].parent_i = i cell_details[new_i]
[new_j].parent_j = j
if not found_dest:
main():
Shreya Sankhwar
A023167022058 1-Y
grid = [
[1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 0, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 1, 1, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1, 0, 0, 1]
# Run A* search
__name__ == "__main__":
main()
Shreya Sankhwar
A023167022058 1-Y
Experiment 2
Aim:- Write a Python code for snakes and ladder (single player) game
Rules:
1. The player starts at position 1.
2. A die (1-6) is rolled, and the player moves forward by that number.
3. If the player lands at the bottom of a ladder, they move up to the top of the ladder.
4. If the player lands on the head of a snake, they slide down to the tail.
5. The game continues until the player reaches or exceeds position 100.
Code-
import random
class SnakesAndLadders:
def __init__(self, name, position=0):
self.name = name
self.position = position
self.ladders = {4: 13, 24: 23, 48: 5, 67: 12, 86: 13}
self.snakes = {6: 4, 26: 6, 47: 7, 23: 5, 55: 8, 97: 9}
def dice(self):
chances = 0
print("\n------ Let's Start the Game ------\n")
if self.position == 104:
print(f"🎉 {self.name} completed the game in {chances+1} turns! 🎉")
break
if self.position in self.ladders:
print(f"🎉 Ladder found at {self.position}, climbing up!")
self.position += self.ladders[self.position]
# Start Game
player = SnakesAndLadders("Zack")
player.dice()
Output-
Shreya Sankhwar
A023167022058 1-Y
Experiment 3
Theory:- play_game() is the main function, which performs the following tasks : Calls
create_board() to create a 3×3 board and initializes with 0.
For each player (1 or 2), calls the random_place() function to randomly choose a location on
board and mark that location with the player number, alternatively.
Print the board after each move.
Evaluate the board after each move to check whether a row or column or diagonal has the
same player number. If so, displays the winner’s name. If after 9 moves, there is no winner
then displays -1.
Shreya Sankhwar
A023167022058 1-Y
Program 1-
# Importing necessary
libraries import numpy as np
import random
from time import sleep
winner = player if
np.all(board != 0) and winner == 0:
winner = -1 # Tie game
return winner
while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print(f"Board after {counter} move(s):")
print(board) sleep(2) counter +=
1 winner = evaluate(board) if
winner != 0:
break
return winner
# Driver Code
print("Winner is:", play_game())
Shreya Sankhwar
A023167022058 1-Y
Output-
Experiment 4
Shreya Sankhwar
A023167022058 1-Y
Aim:- Write a program Implement Brute force solution to the Knapsack problem in Python.
Theory:-
A brute force algorithm is a simple, comprehensive search strategy that systematically
explores every option until a problem’s answer is discovered. It’s a generic approach to
problem-solving that’s employed when the issue is small enough to make an in-depth
investigation possible. However, because of their high temporal complexity, brute force
techniques are inefficient for large-scale issues.
Program 1-
if n == 0 or W == 0:
return 0
# If the weight of the nth item is more than the remaining capacity, exclude it
if wt[n - 1] > W:
# Either include the nth item or exclude it, take the max value
else:
# Example input
W = 50
n = len(val)
Output:
220
Program 2-
else:
include_item = values[n-1] + knapsack_brute_force(capacity-weights[n-1], n-
1) exclude_item = knapsack_brute_force(capacity, n-1) return
max(include_item, exclude_item)
Output:
Shreya Sankhwar
A023167022058 1-Y
Program 3-
Output:
330
Experiment 5
Theory:-
The greedy graph colouring algorithm works by assigning colours to vertices
one at a time, starting from the first vertex. It checks if any neighbouring
vertices share the same colour before colouring a vertex. If a colour can be
assigned without clashing with neighbours, it’s considered a valid part of the
solution. The algorithm continues until all vertices are coloured.
Program 1-
First Fit Algorithm: Arrange the vertices in some arbitrary order and color them in
the arranged order by using proper coloring have provided the steps involved in this
algorithm.
def first_fit_algo(G):
# Get the list of nodes in the graph nodes
= list(G.nodes()) order = len(nodes) # Total
number of nodes
Shreya Sankhwar
A023167022058 1-Y
for j in range(order):
# Example usage
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (1, 2), (1, 3)])
first_fit_algo(G)
Output:
Vertices and its corresponding colors are obtained by using the above method.
Program 2-
Largest Degree Ordering Algorithm : In this algorithm the vertices are ordered in
descending order and proper coloring of the graph is followed in this sequential
manner (Largest first colored).
import networkx as nx
import numpy as np
def largest_degree_order_algo(G):
# Get the list of nodes
nodes = list(G.nodes())
order = len(nodes)
for j in range(order):
if adj[i, j] == 1: # Check adjacency
K.append(color_list[j])
# Example usage
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (1, 2), (1, 3), (3, 4), (4, 5), (5, 6), (4, 6)])
largest_degree_order_algo(G)
Output:
Vertices and its corresponding colors are obtained by using the above method.
Program 3-
Recursive Largest First Algorithm : It uses a recursive structure for coloring the
vertices.
import networkx as nx
import numpy as np
def recursive_lf_algo(G):
nodes = list(G.nodes()) order
= len(nodes)
color_list = [order] * order # Initialize colors with max value
colored_vertex.append(w)
K.append(color_list[m])
# Print results
print("Node Coloring (Recursive LF Algorithm):")
for node, color in result:
Shreya Sankhwar
A023167022058 1-Y
# Example Usage
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (1, 2), (1, 3), (3, 4), (4, 5), (5, 6), (4, 6)])
recursive_lf_algo(G)
Output: Vertices and its corresponding colors are obtained by using the above
method.
Experiment 6
Aim:- Write a program to implement BFS for water jug problem using Python.
Theory:-
The Water Jug Problem is a classic problem in computer science and artificial
intelligence that involves two jugs with different capacities. The goal is to
measure out a specific amount of water using these jugs, which can be filled,
emptied, or poured into one another. The problem can be represented as a
state space search problem, where each state is defined by the amount of
water in each jug.
In this problem, we can use the Breadth-First Search (BFS) algorithm to
explore all possible states (amounts of water in the jugs) until we reach the
desired state (the target amount of water). BFS is particularly suitable for this
Shreya Sankhwar
A023167022058 1-Y
problem because it explores all possible states at the present depth level
before moving on to states at the next depth level, ensuring that the shortest
path to the solution is found.
Program 1-
while queue:
a, b = queue.popleft()
# Possible states
possible_states = [
(capacity_a, b), # Fill Jug A
(a, capacity_b), # Fill Jug B
(0, b), # Empty Jug A
(a, 0), # Empty Jug B
(min(a + b, capacity_a), max(0, b - (capacity_a - a))), # Pour B into A
(max(0, a - (capacity_b - b)), min(a + b, capacity_b)) # Pour A into B
]
Shreya Sankhwar
A023167022058 1-Y
return False
# Example usage
capacity_a = 4
capacity_b = 3
target = 2
if bfs_water_jug(capacity_a, capacity_b,
target): print("Target can be measured.")
else: print("Target cannot be measured.")
Output:
Target can be measured.
Program 2-
while queue:
a, b, path = queue.popleft()
current_path = path + [(a, b)]
Shreya Sankhwar
A023167022058 1-Y
# Possible states
possible_states = [
(capacity_a, b), # Fill Jug A
(a, capacity_b), # Fill Jug B
(0, b), # Empty Jug A
(a, 0), # Empty Jug B
(min(a + b, capacity_a), max(0, b - (capacity_a - a))), # Pour B into A
(max(0, a - (capacity_b - b)), min(a + b, capacity_b)) # Pour A into B
]
return None
# Example usage
capacity_a = 4
capacity_b = 3
target = 2
if path:
print("Target can be measured. Path taken:")
for state in path: print(state) else:
print("Target cannot be measured.")
Output:
Shreya Sankhwar
A023167022058 1-Y
Shreya Sankhwar
A023167022058 1-Y
Experiment 7
Aim:- Write a program to implement DFS for water jug problem using Python.
Program 1-
from collections import deque
while queue:
a, b = queue.popleft()
return True
return False
Output:
Program 2-
import heapq
self.jug_a = jug_a
self.jug_b = jug_b
self.steps = steps
def heuristic(self):
# Simple heuristic: absolute difference from the target
return abs(target - self.jug_a) + abs(target - self.jug_b)
while priority_queue:
current_state = heapq.heappop(priority_queue)
a, b = current_state.jug_a, current_state.jug_b
return False
Experiment 8
Theory:
Tokenization is the process of splitting text into smaller units, such as words or
sentences. It is a fundamental step in Natural Language Processing (NLP) that
helps in analyzing textual data efficiently. The Natural Language Toolkit
(NLTK) is a powerful Python library used for various NLP tasks, including
tokenization.
NLTK provides two main types of tokenization:
1. Word Tokenization: Splits text into individual words. 2.
Sentence Tokenization: Splits text into individual sentences.
Shreya Sankhwar
A023167022058 1-Y
Applications of Tokenization:
• Text Preprocessing in NLP
• Sentiment Analysis
Program 1-
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
# Sample text
text = "Hello! How are you doing today? I hope you're having a great day."
Output-
Sentence Tokenization: ['Hello!', 'How are you?', 'This is an example of tokenization using NLTK.']
Word Tokenization: ['Hello', '!', 'How', 'are', 'you', '?', 'This', 'is', 'an', 'example', 'of', 'tokenization',
'using', 'NLTK', '.']
Program 2-
print("Word Tokenization:", words) import nltk
from nltk.tokenize import word_tokenize, sent_tokenize, regexp_tokenize from
nltk.corpus import stopwords
from nltk.stem import PorterStemmer
text = "NLTK is a powerful Python library! It helps with NLP tasks such as tokenization, stemming,
and stopword removal."
# Removing Stopwords
stop_words = set(stopwords.words("english"))
filtered_words = [word for word in custom_tokens if word.lower() not in stop_words] print("Filtered
Words (No Stopwords):", filtered_words)
Output-
Custom Tokenization (No Punctuation): ['NLTK', 'is', 'a', 'powerful', 'Python', 'library', 'It', 'helps',
'with', 'NLP', 'tasks', 'such', 'as', 'tokenization', 'stemming', 'and', 'stopword', 'removal']
Filtered Words (No Stopwords): ['NLTK', 'powerful', 'Python', 'library', 'helps', 'NLP', 'tasks',
'tokenization', 'stemming', 'stopword', 'removal']
Stemmed Words: ['nltk', 'power', 'python', 'librari', 'help', 'nlp', 'task', 'token', 'stem', 'stopword',
'remov']
Experiment 9
Aim:
To create an XOR truth table using Python and save the results in a Word
document (.docx).
Theory:
Shreya Sankhwar
A023167022058 1-Y
The XOR (Exclusive OR) logic gate outputs true (1) when the number of true
inputs is odd. In a two-input XOR gate, the output is 1 only if one input is 1 and
the other is 0. The truth table for XOR is:
Program 1-
# Save document
Shreya Sankhwar
A023167022058 1-Y
doc.save("XOR_Truth_Table.docx")
Output-
Experiment 10
Aim:
To implement fuzzy logic in AI using Python and the skfuzzy library for decision-making processes.
Theory:
Fuzzy logic is an approach to computing that mimics human reasoning by allowing for approximate
values instead of strict binary logic (True or False, 1 or 0). It is widely used in AI applications,
including decision-making, control systems, and classification problems.
Fuzzy logic consists of the following components:
1. Fuzzification: Converting crisp inputs into fuzzy values using membership functions.
2. Rule Evaluation: Applying IF-THEN rules to determine the output.
3. Defuzzification: Converting fuzzy results back into a crisp value.
Fuzzy logic is useful in AI applications such as expert systems, medical diagnosis, and automatic
control systems (e.g., washing machines, climate control, and robotics).
Code 1-
import numpy as np
import skfuzzy as fuzz
import skfuzzy.control as ctrl
# Control system
fan_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
fanspeed_sim = ctrl.ControlSystemSimulation(fan_ctrl)
OUTPUT-
Code 2-
Shreya Sankhwar
A023167022058 1-Y
import numpy as np
import skfuzzy as fuzz
import skfuzzy.control as ctrl
# Control system
performance_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
performance_sim = ctrl.ControlSystemSimulation(performance_ctrl)
performance_sim.input['grades'] = 90
performance_sim.compute()
print(f"Performance: {performance_sim.output['performance']:.2f}")
OUTPUT-