Ai File
Ai File
Sol:-
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
while queue:
current_node = queue.pop(0) # Dequeue the first node in the queue.
print(current_node, end=" ") # Print the current node.
# Driver Code
print("Breadth-First Search:")
breadth_first_search(visited_nodes, graph, 'A') # Start BFS from node 'A'
OUTPUT
Q-2 Python Program for DFS Algorithm Implementation
Sol:-
# Driver Code
print("Depth-First Search Result:")
depth_first_search(graph, 'A') # Start DFS from node 'A'
OUTPUT:
Q-3 Python implementation of the A* algorithm for solving search problem.
Sol:-
class HelloProblem(SearchProblem):
def actions(self, state):
return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ') if len(state) < len(GOAL) else []
problem = HelloProblem(initial_state='')
result = astar(problem)
print(result.state)
print(result.path())
Q-4 write a python code for A* algorithm demonstration
Sol:-
import heapq
# Define the A* search function with inputs graph, start node, goal node, and heuristics
def custom_astar_search(graph, start, goal, heuristic_fn):
# Initialize the open list with the starting node and a cost of 0
open_nodes = [(0, start)]
# Initialize the closed list as an empty set (nodes already evaluated)
closed_nodes = set()
# Initialize a dictionary to store the cost to reach each node, initially set to infinity
g_costs = {node: float('inf') for node in graph}
# Set the cost to reach the starting node as 0
g_costs[start] = 0
# Initialize a dictionary to store the parent node of each node
parents = {}
# Main loop: continue until there are nodes in the open list
while open_nodes:
# Pop the node with the lowest f_cost (g_cost + heuristic) from the open list
_, current_node = heapq.heappop(open_nodes)
# If the current node is not the goal, add it to the closed list
if current_node not in closed_nodes:
closed_nodes.add(current_node)
# Explore neighbors of the current node and update their g_costs and f_costs
for child, cost in graph[current_node]:
# Calculate the tentative g_cost for the child node
tentative_g_cost = g_costs[current_node] + cost
# If this g_cost is lower than the previously recorded g_cost, update it
if tentative_g_cost < g_costs[child]:
g_costs[child] = tentative_g_cost
# Calculate the f_cost for the child node (g_cost + heuristic)
f_cost = tentative_g_cost + heuristic_fn[child]
# Add the child node to the open list with its f_cost
heapq.heappush(open_nodes, (f_cost, child))
# Record the parent of the child node
parents[child] = current_node
# If the open list becomes empty and the goal is not reached, return None (no path found)
return None
# Define the graph structure (graph) and heuristic values for the nodes
graph_structure = {
'Start': [('A', 1), ('B', 4)],
'A': [('B', 2), ('C', 5), ('D', 12)],
'B': [('C', 2)],
'C': [('D', 3)],
'D': [],
}
heuristic_values = {
'Start': 7,
'A': 6,
'B': 2,
'C': 1,
'D': 0,
}
# Call the custom A* search function to find the path from the start to the goal
resulting_path = custom_astar_search(graph_structure, start_node, goal_node, heuristic_values)
# Print the result: either the path found or a message indicating no path found
if resulting_path:
print("Path from", start_node, "to", goal_node, ":", ' -> '.join(resulting_path))
else:
print("No path found from", start_node, "to", goal_node)
OUTPUT
Q-5 write a python code to create a TIC-TAC-TOE game where a player can play against a
computer opponent that uses the minimax algorithm .
Sol:-
import heapq
# Define the A* search function with inputs graph, start node, goal node, and heuristics
def custom_astar_search(graph, start, goal, heuristic_fn):
# Initialize the open list with the starting node and a cost of 0
open_nodes = [(0, start)]
# Initialize the closed list as an empty set (nodes already evaluated)
closed_nodes = set()
# Initialize a dictionary to store the cost to reach each node, initially set to infinity
g_costs = {node: float('inf') for node in graph}
# Set the cost to reach the starting node as 0
g_costs[start] = 0
# Initialize a dictionary to store the parent node of each node
parents = {}
# Main loop: continue until there are nodes in the open list
while open_nodes:
# Pop the node with the lowest f_cost (g_cost + heuristic) from the open list
_, current_node = heapq.heappop(open_nodes)
# If the current node is not the goal, add it to the closed list
if current_node not in closed_nodes:
closed_nodes.add(current_node)
# Explore neighbors of the current node and update their g_costs and f_costs
for child, cost in graph[current_node]:
# Calculate the tentative g_cost for the child node
tentative_g_cost = g_costs[current_node] + cost
# If this g_cost is lower than the previously recorded g_cost, update it
if tentative_g_cost < g_costs[child]:
g_costs[child] = tentative_g_cost
# Calculate the f_cost for the child node (g_cost + heuristic)
f_cost = tentative_g_cost + heuristic_fn[child]
# Add the child node to the open list with its f_cost
heapq.heappush(open_nodes, (f_cost, child))
# Record the parent of the child node
parents[child] = current_node
# If the open list becomes empty and the goal is not reached, return None (no path found)
return None
# Define the graph structure (graph) and heuristic values for the nodes
graph_structure = {
'Start': [('A', 1), ('B', 4)],
'A': [('B', 2), ('C', 5), ('D', 12)],
'B': [('C', 2)],
'C': [('D', 3)],
'D': [],
}
heuristic_values = {
'Start': 7,
'A': 6,
'B': 2,
'C': 1,
'D': 0,
}
# Call the custom A* search function to find the path from the start to the goal
resulting_path = custom_astar_search(graph_structure, start_node, goal_node,
heuristic_values)
# Print the result: either the path found or a message indicating no path found
if resulting_path:
print("Path from", start_node, "to", goal_node, ":", ' -> '.join(resulting_path))
else:
print("No path found from", start_node, "to", goal_node)
OUTPUT
Q-5 WAP in python to implement Alpha-Beta pruning to find the optimal value of a node.
Sol:-
return value
else: # It's a minimizing node
value = float('inf')
return value
else:
# If the node is not a string, it's a leaf node with a known value
return node
# Call the minimax algorithm with initial values and store the result
optimal_value = minimax_alpha_beta('B', -float('inf'), float('inf'), True)
OUTPUT:
Q-8 WAP in python to draw membership function curve in fuzzy relations of the following
function:
a) Triangular function
b) Gaussian function
c) Trapezoid function
Sol:-
a) For triangular function
b) Gaussian function
Sol: import matplotlib.pyplot as plt
import numpy as np
c) Trapezoid function
Sol:
import matplotlib.pyplot as plt
import numpy as np
OUTPUT:
Q-9 WAP in python using fuzzy logic for a tipping service based on the service and quality factors
Sol:-
import skfuzzy as fuzz
import numpy as np
from skfuzzy import control as ctrl
import matplotlib.pyplot as plt
1), 'tip')
# Pythonic API
tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25])
# Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
# Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
tipping.input['quality'] = 25
tipping.input['service'] = 15
OUTPUT:
Program 10: Python Program for Linear Regression.
Code:
import matplotlib.pyplot as plt
def average(lst):
total = sum(lst)
return avg
# Function to perform linear regression and predict sales for given weeks
x_bar = average(x)
y_bar = average(y)
# Calculate the slope (al) and y-intercept (a0) for the linear regression line
a0 = y_bar - al * x_bar
# Get user input for weeks to predict sales
week_input = input("Enter the week(s) for which you want to predict the sales (separated by
commas): ")
# Plotting the actual values, predicted values, and linear regression line
plt.xlabel('No. of Weeks')
plt.legend()
plt.show()
# Sample data
Output: