AI Python Lab Report CSIT 4th Semester Part II
AI Python Lab Report CSIT 4th Semester Part II
LAB:2
Source Code:
From collections import deque
class Graph:
def __init__(self):
self.graph = {}
neighbors = self.graph[current_node]
for neighbor in neighbors:
if neighbor not in visited:
queue.append(neighbor)
# Example usage:
1 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Output:
Graph:
Source Code:
import heapq
class Graph:
def __init__(self, graph_dict):
self.graph_dict = graph_dict
while priority_queue:
cost, current_node = heapq.heappop(priority_queue)
if current_node == goal_node:
return cost
visited.add(current_node)
2 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
# Example usage:
if cost != -1:
print(f"The cost of the path from {start_node} to {goal_node} is:
{cost}")
else:
print(f"No path found from {start_node} to {goal_node}")
Output:
Graph:
3 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Source Code:
class Graph:
def __init__(self, graph_dict):
self.graph_dict = graph_dict
# Example usage:
4 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Output:
Graph:
Source Code
class Graph:
def __init__(self, graph_dict):
self.graph_dict = graph_dict
if depth_limit <= 0:
return False
5 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
return False
# Example usage:
Output:
6 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Graph:
Source Code:
import heapq
class Node:
def __init__(self, state, parent=None, heuristic=0):
self.state = state
self.parent = parent
self.heuristic = heuristic
while open_list:
current_node = heapq.heappop(open_list)
if current_node.state == goal_state:
return get_path(current_node)
closed_set.add(current_node.state)
7 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
if is_node_in_open_list(successor_node, open_list):
continue
heapq.heappush(open_list, successor_node)
return None
def get_path(node):
path = []
current = node
while current:
path.append(current.state)
current = current.parent
path.reverse()
return path
return False
# Example usage:
# Define the initial state, goal state, and the heuristic function
initial_state = 'A'
goal_state = 'H'
def heuristic(state):
# Define a heuristic function that estimates the cost from the
current state to the goal state
# In this example, we use a simple dictionary to store the heuristic
values for each state
heuristic_values = {
'A': 8,
'B': 6,
'C': 16,
'D': 1,
'E': 2,
'F': 3,
'G': 1,
'H': 0,
}
8 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
return heuristic_values[state]
Output:
Graph:
9 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Source Code:
import heapq
class Node:
def __init__(self, state, parent=None, g=0, h=0):
self.state = state
self.parent = parent
self.g = g # cost from start node to current node
self.h = h # heuristic cost from current node to goal node
self.f = g + h # total cost (f = g + h)
start_node = Node(initial_state)
heapq.heappush(open_list, start_node)
while open_list:
current_node = heapq.heappop(open_list)
if current_node.state == goal_state:
return get_path(current_node)
closed_set.add(current_node.state)
g = current_node.g + cost
h = heuristic(successor, goal_state)
f = g + h
if is_node_in_open_list(successor_node, open_list):
continue
heapq.heappush(open_list, successor_node)
10 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
return None
def get_path(node):
path = []
current = node
while current:
path.append(current.state)
current = current.parent
path.reverse()
return path
return False
# Example usage:
# Define the initial state, goal state, and the heuristic function
initial_state = 'A'
goal_state = 'H'
11 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Output:
Graph:
12 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Source Code:
while True:
neighbors = problem.get_neighbors(current_state)
best_neighbor = None
best_neighbor_cost = float('-inf')
current_state = best_neighbor
return current_state
# Example usage:
# Define the problem class
class Problem:
def __init__(self):
self.initial_state = 3
def get_initial_state(self):
return self.initial_state
13 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Output:
Graph:
8. WAP to solve any one Cryptarithmetic Problem (like TWO +TWO = FOUR or SEND
+MORE = MONEY ). (Recommended Language: Python)
Source Code:
def solve_cryptarithmetic(puzzle):
unique_letters = set(char for word in puzzle for char in word if
char.isalpha())
letters = list(unique_letters)
num_letters = len(letters)
digits = range(10)
14 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
return None
# Example usage:
puzzle = ["TWO", "TWO", "FOUR"]
solution = solve_cryptarithmetic(puzzle)
Output:
Source Code:
#include <iostream>
#include <string>
class Person {
15 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
private:
std::string name;
std::string country;
std::string dateOfBirth;
int height;
int weight;
public:
Person(std::string n, std::string c, std::string dob, int h, int
w)
: name(n), country(c), dateOfBirth(dob), height(h), weight(w)
{}
void displayInformation() {
std::cout << "+------------------------------------------+"
<< std::endl;
std::cout << "| Person |"
<< std::endl;
std::cout << "|------------------------------------------|"
<< std::endl;
std::cout << "| Name: " << name << std::endl;
std::cout << "| Country: " << country << std::endl;
std::cout << "| Date of Birth: " << dateOfBirth << std::endl;
std::cout << "| Height: " << height << " inch" <<
std::endl;
std::cout << "| Weight: " << weight << " kg" <<
std::endl;
std::cout << "+------------------------------------------+"
<< std::endl;
}
};
class Employee {
private:
std::string occupation;
double salary;
std::string company;
std::string location;
public:
Employee(std::string occ, double sal, std::string comp,
std::string loc)
: occupation(occ), salary(sal), company(comp), location(loc)
{}
void displayInformation() {
16 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
int main() {
Person* ram = new Person("Ram", "Nepal", "15th December 1990", 6,
75);
Employee* ramJob = new Employee("AI Researcher", 1.5, "ABC
company", "Kathmandu");
ram->displayInformation();
ramJob->displayInformation();
delete ram;
delete ramJob;
return 0;
}
Output:
17 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Source Code:
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
string country;
string dateOfBirth;
int height;
int weight;
18 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
public:
Person(string n, string c, string dob, int h, int w)
: name(n), country(c), dateOfBirth(dob), height(h), weight(w)
{}
void displayInformation() {
cout << "+------------------------------------------+" <<
endl;
cout << "| Person |" <<
endl;
cout << "|------------------------------------------|" <<
endl;
cout << "| Name: " << name << endl;
cout << "| Country: " << country << endl;
cout << "| Date of Birth: " << dateOfBirth << endl;
cout << "| Height: " << height << " inch" << endl;
cout << "| Weight: " << weight << " kg" << endl;
cout << "+------------------------------------------+" <<
endl;
}
};
class Employee {
private:
string occupation;
double salary;
string company;
string location;
public:
Employee(string occ, double sal, string comp, string loc)
: occupation(occ), salary(sal), company(comp), location(loc)
{}
void displayInformation() {
cout << "+------------------------------------------+" <<
endl;
cout << "| Employee |" <<
endl;
cout << "|------------------------------------------|" <<
endl;
cout << "| Occupation: " << occupation << endl;
cout << "| Salary: " << salary << " lakhs per month"
<< endl;
cout << "| Company: " << company << endl;
cout << "| Location: " << location << endl;
19 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
int main() {
Person ram("Ram", "Nepal", "15th December 1990", 6, 75);
Employee ramJob("AI Researcher", 1.5, "ABC company",
"Kathmandu");
ram.displayInformation();
ramJob.displayInformation();
return 0;
}
Output:
11. WAP to develop a sample medical expert system capable of diagnosing disease based on
the provided symptoms.
20 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Source Code:
class Disease:
def __init__(self, name, symptoms):
self.name = name
self.symptoms = symptoms
class MedicalExpertSystem:
def __init__(self):
self.diseases = []
def add_disease(self, name, symptoms):
disease = Disease(name, symptoms)
self.diseases.append(disease)
21 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Source Code:
import numpy as np
# AND gate
def AND_gate(x1, x2):
# Weight and bias values for the AND gate
weights = np.array([0.5, 0.5])
bias = -0.7
# OR gate
def OR_gate(x1, x2):
# Weight and bias values for the OR gate
weights = np.array([0.5, 0.5])
bias = -0.2
# NOT gate
def NOT_gate(x):
# Weight and bias values for the NOT gate
weight = -0.5
bias = 0.2
22 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
return output
print("\nOR gate:")
print("0 OR 0 =", OR_gate(0, 0))
print("0 OR 1 =", OR_gate(0, 1))
print("1 OR 0 =", OR_gate(1, 0))
print("1 OR 1 =", OR_gate(1, 1))
print("\nNOT gate:")
print("NOT 0 =", NOT_gate(0))
print("NOT 1 =", NOT_gate(1))
Output:
23 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
Source Code:
import numpy as np
24 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
# Example usage:
# Train the network for 10000 epochs with a learning rate of 0.1
network.train(X, y, epochs=10000, learning_rate=0.1)
Output:
14. WAP to solve the N Queen Problem. (Problem: To find an arrangement of N queens on a
chess board of size N×N, such that no queen can attack any other queens on the board)
Source Code:
def is_safe(board, row, col, N):
# Check if there is a queen in the same column
for i in range(row):
if board[i][col] == 1:
25 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
return False
return True
def n_queen(N):
board = [[0 for _ in range(N)] for _ in range(N)]
solve_n_queen(board, 0, N)
Output:
26 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
15. WAP to solve Water Jug Problem.(Problem statement: Given two jugs, a 4-gallon and 3-
gallon having no measuring markers on them. There is a pump that can be used to fill the
jugs with water and the water can be poured on the ground. How can you get exactly 2
gallons of water into 4-gallon jug?
Source Code:
from collections import deque
def water_jug_problem(target):
queue = deque([(0, 0)])
visited = set()
while queue:
jug_state = queue.popleft()
jug1 = jug_state[0]
jug2 = jug_state[1]
if jug1 == target:
return jug_state
if jug_state in visited:
continue
visited.add(jug_state)
# Fill jug1
queue.append((4, jug2))
# Fill jug2
queue.append((jug1, 3))
# Empty jug1
queue.append((0, jug2))
# Empty jug2
27 93/077
BSc.CSIT Artificial Intelligence Sanam Timilsina
queue.append((jug1, 0))
# Pour jug1 to jug2
amount = min(jug1, 3 - jug2)
queue.append((jug1 - amount, jug2 + amount))
# Pour jug2 to jug1
amount = min(jug2, 4 - jug1)
queue.append((jug1 + amount, jug2 - amount))
return None
if result:
print(f"Solution found: {result[0]} gallons in the 4-gallon jug
and {result[1]} gallons in the 3-gallon jug.")
else:
print("Solution not found.")
Output:
28 93/077