Dy Ai Rec
Dy Ai Rec
visited = set()
queue = deque([start])
while queue:
node = queue.pople ()
visited.add(node)
queue.append(neighbor)
if __name__ == "__main__":
# Dynamic input
graph = {}
for _ in range(num_edges):
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
bfs(graph, start_node)
Output:
b. Depth-First Search (DFS)
Program:
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
if __name__ == "__main__":
# Dynamic input
graph = {}
for _ in range(num_edges):
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
dfs(graph, start_node)
Output:
2. Write a program to implement Informed search techniques
a. Greedy Best first search
b. A* algorithm
open_list = []
closed_list = set()
while open_list:
_, current = heapq.heappop(open_list)
if current == goal:
path = []
while current:
path.append(current)
current = came_from[current]
return path[::-1]
closed_list.add(current)
if neighbor in closed_list:
con nue
came_from[neighbor] = current
return None
if __name__ == "__main__":
graph = {}
heuris c = {}
for _ in range(num_edges):
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
for _ in range(num_nodes):
if path:
else:
Output:
b. A* algorithm
Program:
import heapq
open_list = []
closed_list = set()
g_score = {start: 0}
while open_list:
if current == goal:
path = []
while current:
path.append(current)
current = came_from[current]
return path[::-1]
closed_list.add(current)
con nue
if tenta ve_g_score < g_score.get(neighbor, float('inf')) or neighbor not in [i[2] for i in open_list]:
came_from[neighbor] = current
return None
if __name__ == "__main__":
graph = {}
heuris c = {}
num_edges = int(input("Enter number of edges: "))
for _ in range(num_edges):
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
for _ in range(num_nodes):
if path:
else:
Output:
3. Study of Prolog its facts, and rules.
a. Write simple facts for the statements and querying it.
b. Write a program for Family-tree.
Introduc on to Prolog:
Prolog (Programming in Logic) is a high-level programming language based on formal logic. It is widely used in
ar ficial intelligence and computa onal linguis cs. A Prolog program consists of facts, rules, and queries.
cat(tom).
dog(bobby).
bird(tweety).
owns(john, tom).
owns(sarah, bobby).
Queries:
Queries are used to retrieve informa on from the knowledge base.
?- cat(tom).
?- owns(Who, tom).
parent(john, mary).
parent(john, paul).
parent(susan, mary).
parent(susan, paul).
parent(mary, jenny).
parent(mary, jack).
parent(mike, jenny).
parent(mike, jack).
% Facts: gender
male(john).
male(paul).
male(jack).
male(mike).
female(susan).
female(mary).
female(jenny).
Rules:
% Rule: sibling
% Rule: mother
% Rule: father
% Rule: grandparent
% Rule: grandchild
% Rule: ancestor
?- parent(Who, jenny).
?- sibling(paul, mary).
?- ancestor(Who, jack).
% Expected output: Who = mary ; Who = john ; Who = susan ; Who = mike.
4. Write a program to train and validate the following classifiers for given data (scikit-learn):
a. Decision Tree
b. Mul -layer Feed Forward neural network
a. Decision Tree
Program:
import numpy as np
import pandas as pd
# Load dataset
iris = load_iris()
X = iris.data
y = iris.target
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Classifica on Report:")
print(report)
Output:
b. Mul -layer Feed Forward neural network
Program:
from sklearn.neural_network import MLPClassifier
mlp.fit(X_train, y_train)
y_pred_mlp = mlp.predict(X_test)
print("Classifica on Report:")
print(report_mlp)
Output:
5. Text processing using NLTK
a. Remove stop words
b. implement stemming
c. POS (Parts of Speech) tagging
words = word_tokenize(text)
stop_words = set(stopwords.words('english'))
{Sample text:
text = "This is a simple example to demonstrate how to remove stop words from a given text."}
Output:
Original Words: ['This', 'is', 'a', 'simple', 'example', 'to', 'demonstrate', 'how', 'to', 'remove', 'stop', 'words', 'from', 'a',
'given', 'text', '.']
Filtered Words: ['This', 'simple', 'example', 'demonstrate', 'remove', 'stop', 'words', 'given', 'text', '.']
b. implement stemming
Program:
# Ini alize the PorterStemmer
stemmer = PorterStemmer()
Output:
Filtered Words: ['This', 'simple', 'example', 'demonstrate', 'remove', 'stop', 'words', 'given', 'text', '.']
Stemmed Words: ['thi', 'simpl', 'exampl', 'demonstr', 'remov', 'stop', 'word', 'given', 'text', '.']
c. POS (Parts of Speech) tagging
Program:
# POS tagging for the original words
pos_tags = pos_tag(words)
Output:
Original Words: ['This', 'is', 'a', 'simple', 'example', 'to', 'demonstrate', 'how', 'to', 'remove', 'stop', 'words', 'from', 'a',
'given', 'text', '.']
Filtered Words: ['This', 'simple', 'example', 'demonstrate', 'remove', 'stop', 'words', 'given', 'text', '.']
Stemmed Words: ['thi', 'simpl', 'exampl', 'demonstr', 'remov', 'stop', 'word', 'given', 'text', '.']
POS Tags: [('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('simple', 'JJ'), ('example', 'NN'), ('to', 'TO'), ('demonstrate', 'VB'), ('how',
'WRB'), ('to', 'TO'), ('remove', 'VB'), ('stop', 'VB'), ('words', 'NNS'), ('from', 'IN'), ('a', 'DT'), ('given', 'VBN'), ('text', 'NN'),
('.', '.')]
Complete Code:
import nltk
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')
# Sample text
text = "NLTK is a leading pla orm for building Python programs to work with human language data."
words = word_tokenize(text)
stop_words = set(stopwords.words('english'))
# Remove stop words
stemmer = PorterStemmer()
pos_tags = pos_tag(words)
Output:
Original Words: ['NLTK', 'is', 'a', 'leading', 'pla orm', 'for', 'building', 'Python', 'programs', 'to', 'work', 'with', 'human',
'language', 'data', '.']
Filtered Words: ['NLTK', 'leading', 'pla orm', 'building', 'Python', 'programs', 'work', 'human', 'language', 'data', '.']
Stemmed Words: ['nltk', 'lead', 'pla orm', 'build', 'python', 'program', 'work', 'human', 'languag', 'data', '.']
POS Tags: [('NLTK', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('leading', 'VBG'), ('pla orm', 'NN'), ('for', 'IN'), ('building', 'VBG'),
('Python', 'NNP'), ('programs', 'NNS'), ('to', 'TO'), ('work', 'VB'), ('with', 'IN'), ('human', 'JJ'), ('language', 'NN'), ('data',
'NNS'), ('.', '.')]
6. In addi on to the above programs, students should be encouraged to study implementa ons of one of
the following
def print_board(board):
print(" | ".join(row))
print("-" * 5)
def check_winner(board):
return row[0]
return board[0][col]
return board[0][0]
return board[0][2]
# Check for a e
return 'Tie'
return None
# Func on for player's move
def player_move(board):
while True:
board[row][col] = 'X'
break
else:
def bot_move(board):
board[row][col] = 'O'
def c_tac_toe():
print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
# Player's move
player_move(board)
print_board(board)
winner = check_winner(board)
if winner:
break
# Bot's move
bot_move(board)
print_board(board)
winner = check_winner(board)
if winner:
break
if __name__ == "__main__":
c_tac_toe()
Output:
Expert system (Simple Medical Diagnosis) :
Program:
class ExpertSystem:
def __init__(self):
self.symptoms = []
self.condi ons = {
if answer == 'yes':
self.symptoms.append(symptom)
def diagnose(self):
print("\nBased on your symptoms, the possible medical condi ons could be:")
if __name__ == "__main__":
expert_system = ExpertSystem()
expert_system.ask_ques ons()
expert_system.diagnose()
Output:
Text classifica on :
Program:
import numpy as np
# Sample data
texts = ["buy now, limited me offer!", "hey, how are you?", "get free samples today!", "check out our new
products"]
# Feature extrac on
vectorizer = CountVectorizer()
X_train_counts = vectorizer.fit_transform(X_train)
X_test_counts = vectorizer.transform(X_test)
clf.fit(X_train_counts, y_train)
y_pred = clf.predict(X_test_counts)
# Evaluate classifier
print("Accuracy:", accuracy)
print("Classifica on Report:")
print(report)
Output:
Chat bot:
class Chatbot:
def __init__(self):
self.responses = {
"hi": "Hello!",
"default": "I'm sorry, I didn't understand that. Can you please repeat?"
user_input = user_input.lower()
return response
if __name__ == "__main__":
chatbot = Chatbot()
while True:
if user_input.lower() == 'bye':
print(chatbot.get_response(user_input))
break
else:
print("Chatbot:", chatbot.get_response(user_input))
Output: