AI - 5thsem - Manual Updated
AI - 5thsem - Manual Updated
2024-2025
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
bfs(visited, graph, 'A')
Output:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
dfs(visited, graph, 'A')
Output:
class Solution:
def solve(self, board):
state_dict = {}
flatten = []
return self.get_paths(state_dict)
if len(current_nodes) == 0:
return -1
results = []
pos_0 = node.index(0)
for move in moves[pos_0]:
new_node = list(node)
# Swap the 0 with the target position
new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move]
results.append(tuple(new_node))
return results
Output:-
4
.
W
r
i
t
e
import heapq
class Node:
def __init__(self, position, g=0, h=0):
self.position = position
self.g = g # Cost from start node
self.h = h # Heuristic cost to end node
self.f = g + h # Total cost (f = g + h)
self.parent = None
# Priority queue for open list and set for closed list
open_list = []
closed_set = set()
while open_list:
# Get the node with the lowest f value
current_node = heapq.heappop(open_list)
closed_set.add(current_node.position)
# Generate neighbors
for direction in directions:
neighbor_pos = (current_node.position[0] + direction[0], current_node.position[1] +
direction[1])
# Calculate costs
g_cost = current_node.g + 1
h_cost = abs(neighbor_pos[0] - end_node.position[0]) + abs(neighbor_pos[1] -
end_node.position[1])
f_cost = g_cost + h_cost
# Example usage
maze = [
[0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 1, 0],
[0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0],
Dept. of CS&E, AIT Page|8
AI Lab Manual BCS515B
B
[1, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0]
]
start = (0, 0)
end = (5, 6)
path = a_star(maze, start, end)
print("Path found:", path)
Output:
5
.
W
r
i
for v, c in graph[u]:
if visited[v] == False:
visited[v] = True
pq.put((c, v))
print()
# Function for adding edges to graph
def addedge(x, y, cost):
graph[x].append((y, cost))
graph[y].append((x, cost))
# implemented using integers addedge(x,y,cost);
addedge(0, 1, 3)
addedge(0, 2, 6)
addedge(0, 3, 5)
addedge(1, 4, 9)
addedge(1, 5, 8)
addedge(2, 6, 12)
addedge(2, 7, 14)
addedge(3, 8, 7)
addedge(8, 9, 5)
addedge(8, 10, 6)
addedge(9, 11, 1)
addedge(9, 12, 10)
addedge(9, 13, 2)
source = 0
Dept. of CS&E, AIT P a g e | 10
AI Lab Manual BCS515B
B
target = 9
best_first_search(source, target, v)
Output:
import re
class Literal:
# Class Literal, it has attributes name and sign to denote whether the literal is positive or negative in
use
def __init__(self, name, sign=True):
self.name = str(name)
self.sign = sign
def __neg__(self):
return Literal(self.name, False)
def __str__(self):
return str(self.name)
def __repr__(self):
# Returns the string of the literal name, or the string with a negative sign each time the instance
of the literal is called
if self.sign:
return '%r' % str(self.__str__())
else:
return '%r' % str("-" + self.__str__())
def CNFconvert(KB):
# This function converts the KB from a list of sets to a list of lists for easier computing
storage = []
for i in KB:
i = list(i)
for j in i:
j = str(j)
storage.append(i)
return storage
def VariableSet(KB):
# This function finds all the used literals in the KB, to assist with running the DPLL
KB = eval((CNFconvert(KB).__str__()))
storage = []
for obj in KB:
for item in obj:
if item[0] == '-' and item[1:] not in storage:
def Negativeofx(x):
# This function holds the negative form of the literal, for use in the DPLL algorithm
check = re.match("-", str(x))
if check:
return str(x[1:])
else:
return "-" + str(x)
def unitResolution(clauses):
literalholder = {} # Dictionary for holding the literal holder and their boolean values
i=0
while i < len(clauses): # For each clause
newClauses = []
clause = clauses[i]
Dept. of CS&E, AIT P a g e | 13
AI Lab Manual BCS515B
B
# Picks a clause to work on
if len(clause) == 1:
literal = str(clause[0])
pattern = re.match("-", literal)
# Populates the dictionary
if pattern:
nx = literal[1:]
literalholder[nx] = False
else:
nx = "-" + literal
literalholder[literal] = True
# Checks for all other appearances of the literal or its opposite in the KB
for item in clauses:
if item != clauses[i]:
if nx in item:
item.remove(nx)
newClauses.append(item)
i=0
clauses = newClauses
# No unit clause
else:
i += 1
return literalholder, clauses
def DPLL(KB):
# Finally restructures the output to fit the required output by the assignment description
KB = eval((CNFconvert(KB).__str__()))
varList = VariableSet(KB)
result = dpll(KB, varList)
if result == 'notsatisfiable':
return False
else:
for i in varList:
if i in result and result[i] == True:
result[i] = 'true'
elif i in result and result[i] == False:
result[i] = 'false'
else:
result[i] = 'free'
return [True, result]
A = Literal('A')
B = Literal('B')
C = Literal('C')
D = Literal('D')
KB = [{A, B}, {A, -C}, {-A, B, D}]
print(DPLL(KB))
class KnowledgeBase:
def __init__(self):
self.facts = []
self.rules = []
class Predicate:
def __init__(self, name, *args):
self.name = name
self.args = args
def __hash__(self):
return hash((self.name, self.args))
def __repr__(self):
return f"{self.name}({', '.join(map(str, self.args))})"
class Rule:
def __init__(self, antecedent, consequent):
self.antecedent = antecedent # List of conditions
self.consequent = consequent
substituted_antecedent = [
Predicate(cond.name, *[substitution.get(arg, arg) for arg in cond.args])
for cond in self.antecedent
]
kb.tell(query)
return True
# Define individuals
Socrates = "Socrates"
# Define predicates
Human = lambda x: Predicate("Human", x)
Mortal = lambda x: Predicate("Mortal", x)
kb = KnowledgeBase()
kb.tell(Human(Socrates))
kb.add_rule(Rule([Human("x")], Mortal("x")))
class KnowledgeBase:
def __init__(self):
self.rules = []
self.facts = set()
def forward_chain(self):
new_inferences = True
while new_inferences:
new_inferences = False
for antecedent, consequent in self.rules:
# Check if all conditions in the antecedent are true
if all(self.fact_match(cond) for cond in antecedent):
if consequent not in self.facts:
self.tell(consequent)
new_inferences = True
def main():
kb = KnowledgeBase()
if __name__ == "__main__":
main()
Output:
class KnowledgeBase:
def __init__(self):
self.rules = []
self.facts = set()
return False
def main():
kb = KnowledgeBase()
if result:
print(f"{query} is True based on the knowledge base.")
else:
print(f"{query} cannot be proven with the current knowledge base.")
if __name__ == "__main__":
main()
Output:
import re
class SimpleChatBot:
def __init__(self):
self.responses = {
"hello": "Hi there! How can I help you today?",
"hi": "Hello! What can I do for you?",
"how are you": "I'm just a program, but I'm here to help you!",
"what is your name": "I'm a simple chatbot created in Python. What's your name?",
"bye": "Goodbye! Have a great day!",
"default": "I'm sorry, I don't understand that. Could you please rephrase?"
}
def get_response(self, message):
message = message.lower()
def main():
bot = SimpleChatBot()
print("Chatbot: Hello! I am a simple chatbot. Type 'bye' to exit.")
while True:
user_message = input("You: ")
if user_message.lower() == "bye":
print("Chatbot: " + bot.get_response(user_message))
break
response = bot.get_response(user_message)
print("Chatbot: " + response)
if __name__ == "__main__":
main()
Dept. of CS&E, AIT P a g e | 24
AI Lab Manual BCS515B
B
Output: