0% found this document useful (0 votes)
19 views

Ai Lab1

artifivial intelligence practical CSIT sem 4th

Uploaded by

qccqstha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Ai Lab1

artifivial intelligence practical CSIT sem 4th

Uploaded by

qccqstha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

SOURCE CODE:

from collections import deque


def water_jug_problem():
jug1_capacity = int(input("Enter the capacity of the first jug: "))
jug2_capacity = int(input("Enter the capacity of the second jug: "))
target = int(input("Enter the target amount of water: "))
visited = set()
queue = deque([(0, 0, [])]) # (jug1_amount, jug2_amount, path)
while queue:
jug1, jug2, path = queue.popleft()
if (jug1, jug2) in visited:
continue
visited.add((jug1, jug2))
if jug1 == target or jug2 == target:
return path + [(jug1, jug2)]
queue.append((jug1_capacity, jug2, path + [(jug1_capacity, jug2)]))
queue.append((jug1, jug2_capacity, path + [(jug1, jug2_capacity)]))
queue.append((0, jug2, path + [(0, jug2)]))
queue.append((jug1, 0, path + [(jug1, 0)]))
transfer = min(jug1, jug2_capacity - jug2)
queue.append((jug1 - transfer, jug2 + transfer, path + [(jug1 - transfer, jug2 + transfer)]))
transfer = min(jug2, jug1_capacity - jug1)
queue.append((jug1 + transfer, jug2 - transfer, path + [(jug1 + transfer, jug2 - transfer)]))
return None
result = water_jug_problem()
if result:
print("Solution found:")
for step in result:
print(step)
else:
print("No solution found.")

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:

from collections import deque


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
return graph
def bfs(graph, start, goal):
parent = {}
visited = []
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
visited.append(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
queue.append(neighbor)
return None
def main():
graph = create_graph()
start_node = input("Enter the starting node: ")
goal_node = input("Enter the goal node: ")
result = bfs(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 BFS traversal.")
if __name__ == "__main__":
main()

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:

def tower_of_hanoi(n, source, auxiliary, target):


if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n - 1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, source, target)
n = int(input("Enter the number of disks: "))
tower_of_hanoi(n, 'A', 'B', 'C')

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:

You might also like