AI Lab Report CSIT 4th Semester
AI Lab Report CSIT 4th Semester
AI Lab Report CSIT 4th Semester
while queue:
vertex = queue.popleft()
print(vertex, end=' ') # Process the vertex (e.g., print it)
graph = defaultdict(list)
graph[0] = [1, 2]
graph[1] = [2, 3]
graph[2] = [3]
graph[3] = [4, 5]
graph[4] = []
graph[5] = []
print("BFS Traversal:")
bfs(graph, 0)
Output:
1
AI Lab Report 25537 Hridesh Sapkota
import heapq
while queue:
current_cost, current_node = heapq.heappop(queue)
if current_node == goal:
break
if current_node in visited:
continue
visited.add(current_node)
graph = {
'A': [('B', 4), ('C', 2)],
'B': [('A', 4), ('C', 1), ('D', 5)],
'C': [('A', 2), ('B', 1), ('D', 8)],
'D': [('B', 5), ('C', 8), ('E', 3)],
'E': [('D', 3)]
}
start_node = 'A'
goal_node = 'E'
2
AI Lab Report 25537 Hridesh Sapkota
Output:
3
AI Lab Report 25537 Hridesh Sapkota
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['E'],
'D': [],
'E': ['F'],
'F': []
}
print("DFS Traversal:")
visited_nodes = set()
dfs(graph, 'A', visited_nodes)
Output:
4
AI Lab Report 25537 Hridesh Sapkota
visited.add(current_node)
return False
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['E'],
'D': [],
'E': ['F'],
'F': []
}
print("Depth-Limited Search:")
start_node = 'A'
goal_node = 'F'
limit = 3
5
AI Lab Report 25537 Hridesh Sapkota
Output:
if current_node == goal:
return True
visited.add(current_node)
for neighbor, _ in graph[current_node]:
if neighbor not in visited:
priority = heuristic(neighbor, goal)
queue.put((priority, neighbor))
return False
def heuristic(node, goal):
return 0
graph = {
'A': [('B', 5), ('C', 3)],
'B': [('D', 2)],
'C': [('E', 4)],
'D': [],
'E': [('F', 1)],
'F': []
}
start_node = 'A'
goal_node = 'F'
result = gbfs(graph, start_node, goal_node)
if result:
print("Goal node", goal_node, "found.")
else:
print("Goal node", goal_node, "not found.")
6
AI Lab Report 25537 Hridesh Sapkota
Output:
7
AI Lab Report 25537 Hridesh Sapkota
if current_node == goal:
return True
visited.add(current_node)
return False
graph = {
'A': [('B', 4), ('C', 2)],
'B': [('C', 1), ('D', 5)],
'C': [('D', 8)],
'D': [('E', 3)],
'E': []
}
start_node = 'A'
goal_node = 'E'
if result:
8
AI Lab Report 25537 Hridesh Sapkota
Output:
9
AI Lab Report 25537 Hridesh Sapkota
while True:
neighbors = problem.get_neighbors(current_state)
best_neighbor = max(neighbors, key=lambda state:
problem.heuristic(state))
if problem.heuristic(best_neighbor) <=
problem.heuristic(current_state):
return current_state
current_state = best_neighbor
class Problem:
def initial_state(self):
pass
class MyProblem(Problem):
def initial_state(self):
return 0
problem = MyProblem()
solution = hill_climbing(problem)
print("Solution:", solution)
10
AI Lab Report 25537 Hridesh Sapkota
def solve_cryptarithmetic(puzzle):
letters = set()
for word in puzzle:
for letter in word:
letters.add(letter)
letters = sorted(list(letters))
for perm in permutations(range(10), len(letters)):
mapping = {letters[i]: perm[i] for i in range(len(letters))}
if is_solution(puzzle, mapping):
return mapping
return None
solution = solve_cryptarithmetic(puzzle)
if solution:
print("Solution:")
for word in puzzle:
value = 0
for letter in word:
value = value * 10 + solution[letter]
print(word, '=', value)
else:
11
AI Lab Report 25537 Hridesh Sapkota
12
AI Lab Report 25537 Hridesh Sapkota
class Person {
private:
std::string name;
std::string country;
int birthDay;
int birthMonth;
int birthYear;
double height;
double weight;
public:
Person(const std::string& name, const std::string& country, int
birthDay, int birthMonth, int birthYear,
double height, double weight)
: name(name), country(country), birthDay(birthDay),
birthMonth(birthMonth), birthYear(birthYear),
height(height), weight(weight) {}
void display() {
std::cout << name << " is a person living in " << country <<
".\n";
std::cout << "He was born on " << birthDay << "th " <<
getMonthName(birthMonth) << " of year " << birthYear << ".\n";
std::cout << "He is " << height << " inch tall and has " <<
weight << " kg weight.\n";
}
case 3:
return "March";
case 4:
return "April";
case 5:
return "May";
case 6:
return "June";
case 7:
return "July";
case 8:
return "August";
case 9:
return "September";
case 10:
return "October";
case 11:
return "November";
case 12:
return "December";
default:
return "";
}
}
};
class Job {
private:
std::string companyName;
std::string position;
double salary;
public:
Job(const std::string& companyName, const std::string& position,
double salary)
: companyName(companyName), position(position), salary(salary)
{}
void display() {
std::cout << "He has a job. He works at '" << companyName <<
"' as " << position;
std::cout << " and earns " << salary << " lakhs per month.\n";
std::cout << "The company is situated at Kathmandu.\n";
}
};
int main() {
14
AI Lab Report 25537 Hridesh Sapkota
ram->display();
ramJob->display();
delete ram;
delete ramJob;
return 0;
}
Output:
15
AI Lab Report 25537 Hridesh Sapkota
#include <iostream>
#include <string>
class Person {
private:
std::string name;
std::string country;
int birthDay;
int birthMonth;
int birthYear;
double height;
double weight;
public:
Person(const std::string& name, const std::string& country, int
birthDay, int birthMonth, int birthYear,
double height, double weight)
: name(name), country(country), birthDay(birthDay),
birthMonth(birthMonth), birthYear(birthYear),
height(height), weight(weight) {}
void display() {
std::cout << "Person Frame:\n";
std::cout << "Name: " << name << std::endl;
std::cout << "Country: " << country << std::endl;
std::cout << "Birthdate: " << birthDay << "th " <<
getMonthName(birthMonth) << ", " << birthYear << std::endl;
std::cout << "Height: " << height << " inches" << std::endl;
std::cout << "Weight: " << weight << " kg" << std::endl;
}
class Job {
private:
std::string companyName;
std::string position;
double salary;
public:
Job(const std::string& companyName, const std::string& position,
double salary)
: companyName(companyName), position(position), salary(salary)
{}
void display() {
std::cout << "Job Frame:\n";
std::cout << "Company: " << companyName << std::endl;
std::cout << "Position: " << position << std::endl;
std::cout << "Salary: " << salary << " lakhs per month" <<
std::endl;
}
};
int main() {
Person* ram = new Person("Ram", "Nepal", 15, 12, 1990, 6, 75);
ram->display();
std::cout << std::endl;
ramJob->display();
delete ram;
delete ramJob;
return 0;
}
Output:
17
AI Lab Report 25537 Hridesh Sapkota
18
AI Lab Report 25537 Hridesh Sapkota
diseases = {
"flu": ["fever", "cough", "sore throat", "headache"],
"cold": ["sneezing", "runny nose", "congestion"],
"allergies": ["sneezing", "itchy eyes", "runny nose"]
}
def diagnose_disease(symptoms):
matching_diseases = []
return matching_diseases
user_symptoms = ["sneezing", "runny nose"]
19
AI Lab Report 25537 Hridesh Sapkota
diagnosed_diseases = diagnose_disease(user_symptoms)
if diagnosed_diseases:
print("The possible disease(s) based on the provided symptoms
are:")
for disease in diagnosed_diseases:
print("- " + disease)
else:
print("No matching disease found for the provided symptoms.")
Output:
import numpy as np
def step_function(x):
return 1 if x >= 0 else 0
def AND_gate(x1, x2):
w1, w2, b = 0.5, 0.5, -0.7
inputs = np.array([x1, x2])
weighted_sum = np.sum(inputs * np.array([w1, w2]))
output = step_function(weighted_sum + b)
return output
def OR_gate(x1, x2):
w1, w2, b = 0.5, 0.5, -0.2
inputs = np.array([x1, x2])
weighted_sum = np.sum(inputs * np.array([w1, w2]))
output = step_function(weighted_sum + b)
return output
def NOT_gate(x):
w, b = -0.5, 0.2
weighted_sum = x * w
output = step_function(weighted_sum + b)
return output
print("AND Gate")
print(AND_gate(0, 0)) # 0
print(AND_gate(0, 1)) # 0
20
AI Lab Report 25537 Hridesh Sapkota
print(AND_gate(1, 0)) # 0
print(AND_gate(1, 1)) # 1
print("OR Gate")
print(OR_gate(0, 0)) # 0
print(OR_gate(0, 1)) # 1
print(OR_gate(1, 0)) # 1
print(OR_gate(1, 1)) # 1
print("NOT Gate")
print(NOT_gate(0)) # 1
print(NOT_gate(1)) # 0
Output:
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
21
AI Lab Report 25537 Hridesh Sapkota
hidden_error = output_delta.dot(self.weights2.T)
hidden_delta = hidden_error *
sigmoid_derivative(self.hidden_layer)
self.weights2 += self.hidden_layer.T.dot(output_delta) *
learning_rate
self.weights1 += X.T.dot(hidden_delta) * learning_rate
nn = NeuralNetwork(2, 2, 1)
predictions = nn.predict(X)
22
AI Lab Report 25537 Hridesh Sapkota
print(predictions)
Output:
i = row - 1
j = col - 1
while i >= 0 and j >= 0:
if board[i][j] == 1:
return False
i -= 1
j -= 1
i = row - 1
j = col + 1
while i >= 0 and j < N:
if board[i][j] == 1:
return False
i -= 1
23
AI Lab Report 25537 Hridesh Sapkota
j += 1
return True
solve_n_queens_util(board, row + 1, N)
board[row][col] = 0
return False
def solve_n_queens(N):
board = [[0] * N for _ in range(N)]
N = 4
solve_n_queens(N)
Output:
24
AI Lab Report 25537 Hridesh Sapkota
def water_jug_problem():
jug1_capacity = 4
jug2_capacity = 3
target = 2
jug1 = 0
jug2 = 0
path = []
jug1 -= pour_amount
jug2 += pour_amount
path.append((jug1, jug2))
elif jug2 > 0:
jug2 = 0
path.append((jug1, jug2))
return path
solution = water_jug_problem()
Output:
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')
26
AI Lab Report 25537 Hridesh Sapkota
text = "Hello! How are you? I hope you are doing well."
sentences = sent_tokenize(text)
print("Sentence Tokenization:")
for sentence in sentences:
print(sentence)
print()
stop_words = set(stopwords.words('english'))
filtered_words = [word for word in words if word.casefold() not in
stop_words]
print("Stop Words Filtering:")
for word in filtered_words:
print(word)
print()
stemmer = PorterStemmer()
stemmed_words = [stemmer.stem(word) for word in words]
print("Word Stemming:")
for word in stemmed_words:
print(word)
print()
pos_tags = pos_tag(words)
print("POS Tagging:")
for word, tag in pos_tags:
print(word, tag)
print()
Output:
27
AI Lab Report 25537 Hridesh Sapkota
28