Ai Lab1
Ai Lab1
OUTPUT:
SOURCE CODE:
def chatbot():
responses = {
"hello": "Hello there!",
"how are you": "I'm doing well, thanks for asking!",
"what is your name ?": "I'm a simple chatbot",
"exit": "Goodbye!"
}
suggestions = ["Try saying 'hello', 'how are you', or 'what is your name'"]
while True:
user_input = input("You: ").lower()
if user_input == "exit":
print("Chatbot: Goodbye!")
break
if user_input in responses:
print("Chatbot:", responses[user_input])
else:
print("Chatbot: I didn't quite understand that.")
print("Chatbot: Did you mean one of these?")
for suggestion in suggestions:
print(f"- {suggestion}")
if __name__ == "__main__":
chatbot()
OUTPUT:
SOURCE CODE:
OUTPUT:
SOURCE CODE:
def create_graph():
graph = {}
num_nodes = int(input("Enter the number of nodes: "))
for i in range(num_nodes):
node_name = input(f"Enter the name of node {i+1}: ")
neighbors = input(f"Enter the neighbors of node {node_name} (separated by spaces): ").split()
graph[node_name] = neighbors
all_nodes = set(graph.keys())
for neighbors in graph.values():
all_nodes.update(neighbors)
for node in all_nodes:
if node not in graph:
graph[node] = []
return graph
def dfs(graph, start, goal):
visited = set()
parent = {} # To track the path
def dfs_recursive(node):
visited.add(node)
if node == goal:
path = []
while node != start:
path.append(node)
node = parent[node]
path.append(start)
path.reverse()
return path
for neighbor in graph[node]:
if neighbor not in visited:
parent[neighbor] = node
result = dfs_recursive(neighbor)
if result: # If the path is found, return it
return result
return None # Return None if no path is found in this branch
return dfs_recursive(start)
def main():
graph = create_graph()
start_node = input("Enter the starting node: ")
goal_node = input("Enter the goal node: ")
result = dfs(graph, start_node, goal_node)
if result:
print("Path from", start_node, "to", goal_node, ":", result)
else:
print("Goal node", goal_node, "not found in the DFS traversal.")
if __name__ == "__main__":
main()
OUTPUT:
SOURCE CODE:
import heapq
class Graph:
def __init__(self):
self.graph = {}
def add_edge(self, node, neighbor, cost):
if node not in self.graph:
self.graph[node] = []
self.graph[node].append((cost, neighbor))
def best_first_search(self, start, goal):
pq = []
heapq.heappush(pq, (0, start))
visited = set()
costs = {start: 0}
while pq:
current_cost, current_node = heapq.heappop(pq)
if current_node in visited:
continue
visited.add(current_node)
print(f"Visiting Node: {current_node}, Cost: {current_cost}")
if current_node == goal:
print(f"Goal {goal} reached with cost {current_cost}")
return
for edge_cost, neighbor in self.graph.get(current_node, []):
new_cost = current_cost + edge_cost
if neighbor not in visited or new_cost < costs.get(neighbor, float('inf')):
costs[neighbor] = new_cost
heapq.heappush(pq, (new_cost, neighbor))
print("Goal not reachable from start node.")
graph = Graph()
n = int(input("Enter the number of edges: "))
for _ in range(n):
node = input("Enter the node: ")
neighbor = input("Enter the neighbor: ")
cost = int(input(f"Enter the cost to reach {neighbor} from {node}: "))
graph.add_edge(node, neighbor, cost)
start = input("Enter the start node: ")
goal = input("Enter the goal node: ")
graph.best_first_search(start, goal)
OUTPUT:
SOURCE CODE:
OUTPUT;
SOURCE CODE:
import heapq
class Graph:
def __init__(self):
self.graph = {}
def add_edge(self, node, neighbor, cost):
if node not in self.graph:
self.graph[node] = []
self.graph[node].append((cost, neighbor))
def heuristic(self, node, goal):
return abs(ord(goal) - ord(node))
def a_star_algorithm(self, start, goal):
pq = []
heapq.heappush(pq, (0, start))
g_costs = {start: 0} # Actual cost to reach each node
f_costs = {start: self.heuristic(start, goal)} # Estimated total cost
came_from = {} # To reconstruct the path
while pq:
current_f_cost, current_node = heapq.heappop(pq)
if current_node == goal:
print(f"Goal {goal} reached!")
path = self.reconstruct_path(came_from, start, goal)
print(f"Path: {' -> '.join(path)}")
return
for edge_cost, neighbor in self.graph.get(current_node, []):
tentative_g_cost = g_costs[current_node] + edge_cost
if neighbor not in g_costs or tentative_g_cost < g_costs[neighbor]:
came_from[neighbor] = current_node
g_costs[neighbor] = tentative_g_cost
f_costs[neighbor] = tentative_g_cost + self.heuristic(neighbor, goal)
heapq.heappush(pq, (f_costs[neighbor], neighbor))
print("Goal not reachable from start node.")
def reconstruct_path(self, came_from, start, goal):
path = [goal]
while path[-1] != start:
path.append(came_from[path[-1]])
path.reverse()
return path
graph = Graph()
n = int(input("Enter the number of edges: "))
for _ in range(n):
node = input("Enter the node: ")
neighbor = input("Enter the neighbor: ")
cost = int(input(f"Enter the cost to reach {neighbor} from {node}: "))
graph.add_edge(node, neighbor, cost)
start = input("Enter the start node: ")
goal = input("Enter the goal node: ")
# Perform A* Search
graph.a_star_algorithm(start, goal)
OUTPUT: