AI LAB PROGRAMS PART A PROGRAM 1 Write a program to implement Breadth First Search (BFS). from collections import deque def bfs(graph,start): visited=set() queue=deque([start]) visited.add(start) while queue: vertex=queue.popleft() print(vertex,end=" ") for neighbour in graph[vertex]: if neighbour not in visited: queue.append(neighbour) visited.add(neighbour) graph={ 'A ':['B','C'], 'B':['D'], 'C':['E','F'], 'D':[ ], 'E':[ ], 'F':[ ] } print(" \ n BFS order:") bfs(graph,'A') OUTPUT BFS order: A B C D E F PROGRAM 2 Write a program to implement Depth First Search ( D FS). def dfs( graph,start,visited=None): if visited is None: visited=set() visited.add(start) print(start,end=" ") for neighbour in graph[start]: if neighbour not in visited: dfs(graph,neighbour,visited ) graph={ 'A':['B','C'], 'B':['D'], 'C':['E','F'], 'D':[ ], 'E':[ ], 'F':[ ] } print(" \ n DFS order:") dfs(graph,'A') OUTPUT DFS order: A B D C E F PROGRAM 3 Write a Program to Implement 8 - Puzzle problem using Python class Solution: def solve(self, board): dict, flatten = {}, tuple(sum(board, [])) dict[flatten] = 0 if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8): return 0 ret urn self.get_paths(dict) def get_paths(self, dict): cnt = 0 while True: current_nodes = [x for x in dict if dict[x] == cnt] if not current_nodes: return - 1 for node in current_nodes: for move in self.find_next(node): if move not in dict: dict[move] = cnt + 1 if move == (0, 1, 2, 3, 4, 5, 6, 7, 8): return cnt + 1 cnt += 1 def find_next(sel f, node): moves = {0: [1, 3], 1: [0, 2, 4], 2: [1, 5], 3: [0, 4, 6], 4: [1, 3, 5, 7], 5: [2, 4, 8], 6: [3, 7], 7: [4, 6, 8], 8: [5, 7]} pos_0 = node.index(0) return [tuple(node[:move] + (node[pos_0],) + node[move+1:pos_0] + (node[move],) + node[pos_0+1:]) for move in moves[pos_0]] ob = Solution() matrix = [[3, 1, 2], [4, 7, 5], [6, 8, 0]] print(ob.solve(matrix)) OUTPUT : 4 PROGRAM 4 Write a program to implement N - queens problem using python. N = 4 def printSolution(board): for row in board: print(' '.join(map(str, row)) ) def isSafe(board, row, col): for i in range(col): if board[row][i] == 1: return False for i, j in zip(range(row, - 1, - 1), range(col, - 1, - 1)): if board[i][j] == 1: return False for i, j in zip(range(row, N), range(col, - 1, - 1)): if board[i][j] == 1: return False return True def solveNQUtil(board, col): if col >= N: return True for i in range(N): if isSafe(board, i, col): board[i][col] = 1 if solveNQUtil (board, col + 1): return True board[i][col] = 0 return False def solveNQ(): board = [[0] * N for _ in range(N)] if solveNQUtil(board, 0): printSolution(board) else: print("Solution does not exist") solveNQ() OUTPUT 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 PROGRAM 5 Write a Program to Implement Alpha - Beta Pruning using Python MAX = 1000 MIN = - 1000 def minimax(depth, nodeIndex, maximizingPlayer, values, alpha, beta): if depth == 3: return values[nodeIndex] best = MIN if maximizingPlayer else MAX for i in range(2): val = minimax(depth + 1, nodeIndex * 2 + i, not maximizingPlayer, values, alpha, beta) if maximizingPlayer: best = max(best, val) alpha = max(al pha, best) else: best = min(best, val) beta = min(beta, best) if beta <= alpha: break return best if __name__ == "__main__": values = [3, 5, 6, 9, 1, 2, 0, - 1] print("Optimal v alue is:", minimax(0, 0, True, values, MIN, MAX)) OUTPUT Optimal value is: 5 PART B PROGRAM 1 Write a program to implement forward chaining algorithm. database = ["Croaks", "Eat Flies", "Shrimps", "Sings"] knowbase = ["Frog", "Canary", "Green", "Yellow"] def display(): print(""" X is: 1. Croaks 2. Eat Flies 3. Shrimps 4. Sings Select one option (1 - 4): """, end="") def main(): print("* --- Forward Chaining --- *") display() try: x = int(input()) if x not in [1, 2, 3, 4]: print(" \ n ---- Invalid option, select again ----- ") return print(f" \ nX is {database[x - 1]}") print(" \ nColor is: \ n1. Green \ n2. Yellow \ nSelect option (1 - 2): ", end="") k = int(input()) if (x == 1 or x == 2) and k == 1: print(f" \ nYes, it is {knowbase[0]} and Color is {knowbase[2]}") elif (x == 3 or x == 4) and k == 2: print(f" \ nYes, i t is {knowbase[1]} and Color is {knowbase[3]}") else: print(" \ n -- Invalid knowledge combination -- ") except ValueError: print(" \ n -- Please enter a valid number -- ") if __name__ == "__main__": main() OUTPUT * --- Forw ard Chaining --- * X is: 1. Croaks 2. Eat Flies 3. Shrimps 4. Sings Select one option (1 - 4): 1 X is Croaks Color is: 1. Green 2. Yellow Select option (1 - 2): 3 -- Invalid knowledge combination -- PROGRAM 2 Write a program to implement forward chaining algorithm. database = ["Croaks", "Eat Flies", "Shrimps", "Sings"] knowbase = ["Frog", "Canary", "Green", "Yellow"] def display(): print(""" X is: 1. Croaks 2. Eat Flies 3. Shrimps 4. Sings Select one option (1 - 4): """, end="") def main() : print("* --- Forward Chaining --- *") display() try: x = int(input()) if x not in [1, 2, 3, 4]: print(" \ n ---- Invalid option, select again ----- ") return print(f" \ nX is {database[x - 1]}") print(" \ nColor is: \ n1. Green \ n2. Yellow \ nSelect option (1 - 2): ", end="") k = int(input()) if (x in [1, 2]) and k == 1: print(f" \ nYes, it is {knowbase[0]} and Color is {knowbase[2]}") elif (x in [3, 4]) and k == 2: print(f" \ nYes, it is {knowbase[1]} and Color is {knowbase[3]}") else: print(" \ n -- Invalid knowledge combination -- ") except ValueError: print(" \ n -- Please enter a valid number -- ") if __name__ == "__main__": main() OUTPUT * --- Forward Chaining --- * X is: 1. Croaks 2. Eat Flies 3. Shrimps 4. Sings Select one option (1 - 4): 4 X is Sings Color is: 1. Green 2. Yellow Select option (1 - 2): 2 Yes, it is Canary and Color is Yellow [ ]: PROGRAM 3 Train a random data sample using linear regression model and plot the graph. note: before executing program install required libraries COMMAND TO INSTALL “ pip install numpy matplotlib scikit - learn ” import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1) model = LinearRegression().fit(X, y) X_new = np.array([[0], [2]]) y_pred = model.predict(X_new) plt.scatter(X, y) plt.plot(X_new, y_pred, color='red') plt.show() OUTPUT PROGRAM 4 Implement the naïve Bayesian classifier for a sample training data set stored as a .csv file. Compute the accuracy of the classifier, considering few test data sets. note: before executing program install required libraries and iris dataset COMMAND TO INSTALL “ pip install numpy pandas scikit - learn ” import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.datasets import load_iris # Load buil t - in Iris dataset iris = load_iris() X = iris.data y = iris.target # Split dataset into training and testing X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Feature Scaling scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # Train and evaluate model model = GaussianNB().fit(X_train, y_train) y_pred = model.predict(X_test) print("Accuracy:", accuracy_score(y_test, y_pred)) print("Confus ion Matrix: \ n", confusion_matrix(y_test, y_pred)) OUTPUT Accuracy: 1.0 Confusion Matrix: [[10 0 0] [ 0 9 0] [ 0 0 11]] PROGRAM 5 Demonstrate the working of SVM classifier for a suitable data set (e.g., iris dataset) note: before executing program install required libraries COMMAND TO INSTALL “ pip install numpy matplotlib scikit - learn ” import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preproc essing import StandardScaler from sklearn.svm import SVC from sklearn.metrics import accuracy_score, confusion_matrix # Load Iris dataset from sklearn iris = load_iris() X, y = pd.DataFrame(iris.data, columns=iris.feature_names), iris.target # Split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Scale the features scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # Train SVM classifier svm_classifier = SVC(kernel='linear', random_state=42) svm_classifier.fit(X_train, y_train) y_pred = svm_classifier.predict(X_test) # Evaluate the model print("Accuracy:", accuracy_score(y_test, y_pred)) print("Confusion Matrix: \ n", confus ion_matrix(y_test, y_pred)) OUTPUT Accuracy: 0.9666666666666667 Confusion Matrix: [[10 0 0] [ 0 8 1] [ 0 0 11]]