FACULTY OF ENGINEERING AND TECHNOLOGY
BACHELOR OF TECHNOLOGY
Artificial Intelligence Laboratory
(303105308)
SEMESTER V
Artificial Intelligence & Data Science
Department
CERTIFICATE
This is to certify that
Ms. Nesee Rajpopat with Enrollment No. 2403031247024
has successfully completed her laboratory experiments in the Artificial
Intelligence Lab (303105308) from the department of Artificial
Intelligence & Data Science during the academic year 2025- 2026.
Date of Submission ….…………… Staff In charge …..……………
Head of Department………….……
TABLE OF CONTENTS
[Link] Experiment Page No Date of Date of Marks Sign
Title Perfomance Submission
From To
1 Develop an AI-based medical diagnosis system using
expert systems architecture and knowledge
representation techniques.
2 Build an intelligent agent for optimizing e-commerce
inventory management using search algorithms like hill
climbing and best-first search.
3 Implement a constraint satisfaction algorithm to solve
scheduling problems in healthcare facilities
4 Create a recommendation system for personalized
learning using means-end analysis and heuristic search
techniques.
5 Develop a problem-solving agent for optimizing
resource allocation in logistics using A* and AO*
algorithms.
6 Develop a fuzzy logic-based system for predicting
stock market trends considering uncertain market
conditions.
7 Write a program to implement BFS (Water Jug
problem or any AI search problem).
Write a program to implement DFS (Water Jug
problem or any AI search problem).
8 Define a predicate brother(X,Y) which holds iff X and
Y are brothers.
Define a predicate cousin(X,Y) which holds iff X and
Y are cousins.
Define a predicate grandson(X,Y) which holds iff X is
a grandson of Y.
Define a predicate descendent(X,Y) which holds iff X
is a descendent of Y.
Consider the following genealogical tree:
father(a,b).
father(a,c).
father(b,d).
father(b,e).
father(c,f).
Say which answers, and in which order, are generated
by your definitions for the following queries in Prolog:
?- brother(X,Y).
?- cousin(X,Y).
?- grandson(X,Y).
?- descendent(X,Y).
9 Write a program to implement Tic-Tac-Toe game using
python.
10 Create a spell-checking application utilizing natural
language processing (NLP) techniques, including
syntactic and semantic analysis.
11 Design a neural network architecture for pattern
recognition in medical imaging for disease diagnosis.
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
PRACTICAL: 01
Aim: Develop an AI-based medical diagnosis system using expert systems
architecture and knowledge representation techniques.
Program:
known_symptoms = {"fever", "cough", "headache", "sore_throat", "body_aches"}
diseases = {
"flu": {"fever", "cough", "body_aches"},
"cold": {"fever", "cough", "sore_throat"},
"tension_headache": {"headache"}
}
def collect_symptoms():
print("Enter symptoms (comma-separated), e.g., fever,cough:")
user_input = input().lower()
patient_symptoms = {[Link]() for sym in user_input.split(",")}
if not patient_symptoms.issubset(known_symptoms):
print("\nUnknown symptoms detected. Valid symptoms are:", known_symptoms)
return None
return patient_symptoms
def collect_symptoms():
print("Enter symptoms (comma-separated), e.g., fever,cough:")
user_input = input().lower()
patient_symptoms = {[Link]() for sym in user_input.split(",")}
if not patient_symptoms.issubset(known_symptoms):
print("\nUnknown symptoms detected. Valid symptoms are:", known_symptoms)
return None
return patient_symptoms
5|Pa g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
def diagnose():
patient_symptoms = collect_symptoms()
if not patient_symptoms:
return
diagnosed = False
for disease, symptoms in [Link]():
if [Link](patient_symptoms):
print(f"\n The patient may have: {[Link]()}")
diagnosed = True
if not diagnosed:
print("\n Unable to diagnose the disease based on provided symptoms.")
diagnose()
OUTPUT:
6|Pa g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
PRACTICAL: 02
Aim: Build an intelligent agent for optimizing e-commerce inventory
management using search algorithms like hill climbing and best-first search.
Program:
def demand(price):
return max(0, 1000 - 5 * price)
def calculate_revenue(prices):
return sum(price * demand(price) for price in prices)
def get_neighbors(prices):
neighbors = []
for i, price in enumerate(prices):
for change in [-10, 10]:
new_prices = [Link]()
new_prices[i] += change
[Link](new_prices)
return neighbors
def hill_climb(prices):
current = prices
current_revenue = calculate_revenue(current)
while True:
neighbors = get_neighbors(current)
next_state = max(neighbors, key=calculate_revenue)
next_revenue = calculate_revenue(next_state)
if next_revenue > current_revenue:
current, current_revenue = next_state, next_revenue
else:
7|Pa g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
break
return current, current_revenue
initial_prices = [100, 150, 200, 250]
optimal_prices, max_revenue = hill_climb(initial_prices)
print(" Optimal prices:", optimal_prices)
print(" Maximum revenue:", max_revenue)
OUTPUT:
8|Pa g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
PRACTICAL: 03
Aim: Implement a constraint satisfaction algorithm to solve scheduling
problems in Healthcare facilities
Program:
availability = {
'Morning': ['Dr. Kunj', 'Dr. Jitesh'],
'Afternoon': ['Dr. Kunj', 'Dr. Dhairya'],
'Night': ['Dr. Dhairya', 'Dr. Jitesh', 'Dr. Naitik'],
'MidEvening': ['Dr. Naitik']
}
def all_different(assignments):
return len(set(assignments)) == len(assignments)
from itertools import permutations
def schedule():
shifts = ['Morning', 'Afternoon', 'Night', 'MidEvening']
domains = [availability[shift] for shift in shifts]
for perm in permutations([doctor for sublist in domains for doctor in sublist], 4):
assignment = dict(zip(shifts, perm))
if all_different([Link]()):
print(" Valid Schedule Found:")
for shift in shifts:
print(f" - {shift}: {assignment[shift]}")
return
print(" No valid schedule found.")
schedule()
9|Pa g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
Output:
10 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
PRACTICAL: 04
Aim: Create a recommendation system for personalized learning using means-
end analysis and heuristic search techniques.
Program:
users = {
'kunj': {'interest': ['tech', 'workout'], 'age': 19, 'location': 'india'},
'jitesh': {'interest': ['books', 'travel'], 'age': 21, 'location': 'usa'},
'dhairya': {'interest': ['tech', 'travel'], 'age': 18, 'location': 'germany'}
}
def get_recommendations(user_name):
user = [Link](user_name.lower())
if not user:
print("User not found.")
return []
rec = []
if 'tech' in user['interest']:
[Link](['Smartphone', 'Laptop'])
if 'books' in user['interest']:
[Link](['E-Reader', 'Kindle'])
if 'workout' in user['interest']:
[Link]('Gym')
if user['age'] < 30:
[Link]('Gaming Console')
if user['location'] == 'usa':
[Link]('Amazon Prime Membership')
elif user['location'] == 'india':
[Link]('Netflix Membership')
elif user['location'] == 'germany':
[Link]('Disney+ Membership')
11 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
return rec
user_input = input("Enter user name (kunj, jitesh, dhairya): ")
recommendations = get_recommendations(user_input)
print("\n Recommendations for", user_input.capitalize(), ":", recommendations)
OUTPUT:
12 | P a g e
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
PRACTICAL: 05
Aim: Use A* Algorithm to find Optimal Resource allocation Path in a Logistic
Graph.
import heapq
# Heuristic values
heuristics = {
'a': 5,
'b': 4,
'c': 2,
'd': 1,
'e': 0
}
# Graph: adjacency list with weights
graph = {
'a': [('b', 1), ('c', 2)],
'b': [('c', 1), ('d', 2)],
'c': [('d', 1), ('e', 2)],
'd': [('e', 1)],
'e': []
}
# A* Algorithm
def a_star(start, goal):
open_list = []
[Link](open_list, (heuristics[start], 0, start, []))
while open_list:
est_total, cost_so_far, current, path = [Link](open_list)
path = path + [current]
print("Visiting:", path)
if current == goal:
return path, cost_so_far
for neighbor, cost in graph[current]:
new_cost = cost_so_far + cost
est = new_cost + heuristics[neighbor]
[Link](open_list, (est, new_cost, neighbor, path))
return None, float('inf')
# Run A* search
path, total_cost = a_star('a', 'e')
print("\nFinal Path:", path)
print("Total Cost:", total_cost)
13 2403031247024
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
Output:
14 2403031247024
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
PRACTICAL: 06
Aim: Predict Market Trends using Fuzzy Logic with Sentiment, Volume and
Voltality.
sentiment_scores = {'positive': 0.7, 'neutral': 0.5, 'negative': 0.3}
volume_scores = {'high': 0.8, 'medium': 0.5, 'low': 0.2}
volatility_scores = {'large': 0.7, 'mid': 0.5, 'small': 0.3}
def predict_trend(volume, volatility, sentiment):
s = sentiment_scores[sentiment]
v = volume_scores[volume]
vol = volatility_scores[volatility]
overall = (s + v + vol) / 3
if overall > 0.6 and overall < 0.7:
return 'bullish'
elif overall > 0.7:
return 'fishy'
elif overall < 0.3:
return 'lowkey'
elif overall < 0.4 and overall > 0.3:
return 'bearish'
else:
return 'neutral'
# Example input
trend = predict_trend('low', 'small', 'negative')
print(" Predicted Market Trend:", trend)
Output:
15 2403031247024
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
PRACTICAL: 07
Aim: Implement BFS for the Water Jug problem (4L & 3L jugs). Implement DFS
for the same problem.
from collections import deque
from typing import List, Tuple, Optional, Set, Dict
CAP1, CAP2 = 4, 3 # Jug capacities
INITIAL: Tuple[int, int] = (0, 0)
def is_goal(state: Tuple[int, int]) -> bool:
x, y = state
return x == 2 # Goal: Jug1 has exactly 2 liters
def print_path(path: List[Tuple[int, int]]) -> None:
for s in path:
print(s)
def next_states(state: Tuple[int, int]) -> List[Tuple[int, int]]:
x, y = state
succ = []
# 1) Fill Jug1
if x < CAP1:
[Link]((CAP1, y))
# 2) Fill Jug2
if y < CAP2:
[Link]((x, CAP2))
# 3) Empty Jug1
if x > 0:
[Link]((0, y))
# 4) Empty Jug2
if y > 0:
[Link]((x, 0))
# 5) Pour Jug2 -> Jug1
if x + y <= CAP1 and y > 0:
[Link]((x + y, 0))
if x + y > CAP1 and y > 0 and x < CAP1:
[Link]((CAP1, y - (CAP1 - x)))
# 6) Pour Jug1 -> Jug2
if x + y <= CAP2 and x > 0:
[Link]((0, x + y))
if x + y > CAP2 and x > 0 and y < CAP2:
[Link]((x - (CAP2 - y), CAP2))
# Remove duplicates (if any)
return list([Link](succ))
16 2403031247024
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
def bfs(initial: Tuple[int, int]) -> Optional[List[Tuple[int, int]]]:
if is_goal(initial):
return [initial]
q = deque([initial])
visited: Set[Tuple[int, int]] = {initial}
parent: Dict[Tuple[int, int], Optional[Tuple[int, int]]] = {initial: None}
while q:
s = [Link]()
for ns in next_states(s):
if ns not in visited:
[Link](ns)
parent[ns] = s
if is_goal(ns):
# Reconstruct path
path = [ns]
cur = ns
while parent[cur] is not None:
cur = parent[cur]
[Link](cur)
[Link]()
return path
[Link](ns)
return None
def dfs(initial: Tuple[int, int]) -> Optional[List[Tuple[int, int]]]:
visited: Set[Tuple[int, int]] = set()
def dfs_util(state: Tuple[int, int], path: List[Tuple[int, int]]) -> Optional[List[Tuple[int, int]]]:
if is_goal(state):
return path + [state]
[Link](state)
for ns in next_states(state):
if ns not in visited:
res = dfs_util(ns, path + [state])
if res is not None:
return res
return None
return dfs_util(initial, [])
# Run BFS
bfs_path = bfs(INITIAL)
if bfs_path is None:
print("No solution found by BFS.")
else:
print("BFS Path:")
print_path(bfs_path)
print("Moves:", len(bfs_path) - 1)
# Run DFS
dfs_path = dfs(INITIAL)
if dfs_path is None:
print("No solution found by DFS.")
17 2403031247024
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
else:
print("DFS Path:")
print_path(dfs_path)
print("Moves:", len(dfs_path) - 1)
Output:
18 2403031247024
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
PRACTICAL: 08
Aim: Given the following Prolog facts:
father(a, b).
father(a, c).
father(b, d).
father(b, e).
father(c, f).
Define the following predicates:
1. brother(X, Y): X and Y are brothers.
2. cousin(X, Y): X and Y are cousins.
3. grandson(X, Y): X is a grandson of Y.
4. descendent(X, Y): X is a descendant of Y.
#Cell: Define facts
father_facts = [('a','b'),('a','c'),('b','d'),('b','e'),('c','f')]
print('Father facts:')
for f,c in father_facts:
print(f'father({f},{c}).')
# brother(X,Y)
def brother_pairs(facts):
for F,X in facts:
for F2,Y in facts:
if F2==F and X!=Y:
yield (X,Y)
print('Query brother:')
print(list(brother_pairs(father_facts)))
# cousin(X,Y)
def is_brother_of(p1,p2,facts):
for Z,child1 in facts:
if child1==p1:
for Z2,child2 in facts:
if Z2==Z and child2==p2 and p1!=p2:
return True
return False
def cousin_pairs(facts):
for F1,X in facts:
for F2,Y in facts:
if is_brother_of(F1,F2,facts):
yield (X,Y)
print('Query cousin:')
print(list(cousin_pairs(father_facts)))
# grandson(X,Y)
def grandson_pairs(facts):
for Y,P in facts:
for P2,X in facts:
if P2==P:
yield (X,Y)
19 2403031247024
Faculty of Engineering & Technology
Subject: Artificial Intelligence Laboratory
Subject Code: 303105308
[Link] - CSE 3rd Year 5th Semester
print('Query grandson:')
print(list(grandson_pairs(father_facts)))
# descendant(X,Y)
def descendants_of(node,facts):
for F,C in facts:
if F==node:
yield C
for F,C in facts:
if F==node:
for deeper in descendants_of(C,facts):
yield deeper
def descendant_pairs_prolog(facts):
for F,C in facts:
yield (C,F)
for Y,P in facts:
for X in descendants_of(P,facts):
yield (X,Y)
print('Query descendant:')
print(list(descendant_pairs_prolog(father_facts)))
Output:
20 2403031247024