Programs for AI
Programs for AI
Program:
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:-
A
B
D
E
F
C
2. Write a Program to Implement Depth First Search using Python.
Program:
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:
A
B
D
E
F
C
Program:
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
Program:
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()
# 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
start = (0, 0)
end = (5, 6)
Output:
Path found: [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (3, 2), (4, 2), (5, 2), (5, 3),
(5, 4), (5, 5), (5, 6)]
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))
# The nodes shown in above example(by alphabets) are
# 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
target = 9
best_first_search(source, target, v)
Output:
013289
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):
# Returns a new literal with the same name but the opposite
sign of its parent literal
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:
storage.append(str(item[1:]))
elif item not in storage and item[0] != '-':
storage.append(str(item))
return 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
# This part of the code goes through each and every clause until all
literals in the KB are resolved
while i < len(clauses): # For each clause
newClauses = []
clause = clauses[i]
# 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))
Output:
[True, {'B': 'true', 'A': True, 'C': 'free', 'D': 'free'}]
Program:
class KnowledgeBase:
def __init__(self):
self.facts = []
self.rules = []
class Predicate:
def __init__(self, name, *args):
self.name = name
self.args = args
def __eq__(self, other):
return self.name == other.name and self.args == other.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
kb.tell(query)
return True
# Define individuals
Socrates = "Socrates"
# Define predicates
Human = lambda x: Predicate("Human", x)
Mortal = lambda x: Predicate("Mortal", x)
# Create a knowledge base
kb = KnowledgeBase()
Output:
Mortal(Socrates) is True
Program:
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:
Criminal(West) is True based on the knowledge base.
9. Write a program to implement backward chaining algorithm
using Python
Program:
class KnowledgeBase:
def __init__(self):
self.rules = []
self.facts = set()
return False
if __name__ == "__main__":
main()
Output:
Criminal(West) is True based on the knowledge base.
Program:
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 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()
Output:
Chatbot: Hello! I am a simple chatbot. Type 'bye' to exit.
You: Hello
Chatbot: Hi there! How can I help you today?
You: What is your name
Chatbot: I'm a simple chatbot created in Python. What's your name?
You: Harry
Chatbot: I'm sorry, I don't understand that. Could you please
rephrase?
You: My name is Harry
Chatbot: I'm sorry, I don't understand that. Could you please
rephrase?
You: Bye
Chatbot: Goodbye! Have a great day!