├── 8tile.py ├── Alpha-Beta pruning.py ├── Astar.py ├── bfs.py ├── chatbot.py ├── chatbot2.py ├── dfs.py ├── fuzzy.py ├── nim_game.py ├── tic tac toe.py └── tsp.py /8tile.py: -------------------------------------------------------------------------------- 1 | import copy 2 | from heapq import heappush, heappop 3 | n = 3 4 | row = [ 1, 0, -1, 0 ] 5 | col = [ 0, -1, 0, 1 ] 6 | class priorityQueue: 7 | def __init__(self): 8 | self.heap = [] 9 | def push(self, k): 10 | heappush(self.heap, k) 11 | def pop(self): 12 | return heappop(self.heap) 13 | def empty(self): 14 | if not self.heap: 15 | return True 16 | else: 17 | return False 18 | class node: 19 | def __init__(self, parent, mat, empty_tile_pos, 20 | cost, level): 21 | self.parent = parent 22 | self.mat = mat 23 | self.empty_tile_pos = empty_tile_pos 24 | self.cost = cost 25 | self.level = level 26 | def __lt__(self, nxt): 27 | return self.cost < nxt.cost 28 | def calculateCost(mat, final) -> int: 29 | count = 0 30 | for i in range(n): 31 | for j in range(n): 32 | if ((mat[i][j]) and 33 | (mat[i][j] != final[i][j])): 34 | count += 1 35 | return count 36 | def newNode(mat, empty_tile_pos, new_empty_tile_pos, 37 | level, parent, final) -> node: 38 | new_mat = copy.deepcopy(mat) 39 | x1 = empty_tile_pos[0] 40 | y1 = empty_tile_pos[1] 41 | x2 = new_empty_tile_pos[0] 42 | y2 = new_empty_tile_pos[1] 43 | new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1] 44 | cost = calculateCost(new_mat, final) 45 | new_node = node(parent, new_mat, new_empty_tile_pos, 46 | cost, level) 47 | return new_node 48 | def printMatrix(mat): 49 | for i in range(n): 50 | for j in range(n): 51 | print("%d " % (mat[i][j]), end = " ") 52 | print() 53 | def isSafe(x, y): 54 | return x >= 0 and x < n and y >= 0 and y < n 55 | def printPath(root): 56 | if root == None: 57 | return 58 | printPath(root.parent) 59 | printMatrix(root.mat) 60 | print() 61 | def solve(initial, empty_tile_pos, final): 62 | pq = priorityQueue() 63 | cost = calculateCost(initial, final) 64 | root = node(None, initial, 65 | empty_tile_pos, cost, 0) 66 | pq.push(root) 67 | while not pq.empty(): 68 | minimum = pq.pop() 69 | if minimum.cost == 0: 70 | printPath(minimum) 71 | return 72 | for i in range(4): 73 | new_tile_pos = [ 74 | minimum.empty_tile_pos[0] + row[i], 75 | minimum.empty_tile_pos[1] + col[i], ] 76 | if isSafe(new_tile_pos[0], new_tile_pos[1]): 77 | child = newNode(minimum.mat, 78 | minimum.empty_tile_pos, 79 | new_tile_pos, 80 | minimum.level + 1, 81 | minimum, final,) 82 | pq.push(child) 83 | initial = [ [ 1, 2, 3 ], 84 | [ 5, 6, 0 ], 85 | [ 7, 8, 4 ] ] 86 | final = [ [ 1, 2, 3 ], 87 | [ 5, 8, 6 ], 88 | [ 0, 7, 4 ] ] 89 | empty_tile_pos = [ 1, 2 ] 90 | solve(initial, empty_tile_pos, final) 91 | -------------------------------------------------------------------------------- /Alpha-Beta pruning.py: -------------------------------------------------------------------------------- 1 | import math 2 | # Represents the game tree nodes 3 | class Node: 4 | def __init__(self, value=None): 5 | self.value = value 6 | self.children = [] 7 | # Minimax algorithm with alpha-beta pruning 8 | def minimax_alpha_beta(node, depth, alpha, beta, maximizingPlayer): 9 | if depth == 0 or len(node.children) == 0: 10 | return node.value 11 | if maximizingPlayer: 12 | value = -math.inf 13 | for child in node.children: 14 | value = max(value, minimax_alpha_beta(child, depth - 1, alpha, beta, False)) 15 | alpha = max(alpha, value) 16 | if alpha >= beta: 17 | break 18 | return value 19 | else: 20 | value = math.inf 21 | for child in node.children: 22 | value = min(value, minimax_alpha_beta(child, depth - 1, alpha, beta, True)) 23 | beta = min(beta, value) 24 | if beta <= alpha: 25 | break 26 | return value 27 | # Example usage 28 | if __name__ == "__main__": 29 | # Construct a simple game tree 30 | root = Node() 31 | root.value = 3 32 | node1 = Node() 33 | node1.value = 5 34 | root.children.append(node1) 35 | node2 = Node() 36 | node2.value = 6 37 | root.children.append(node2) 38 | node3 = Node() 39 | node3.value = 9 40 | node1.children.append(node3) 41 | node4 = Node() 42 | node4.value = 1 43 | node1.children.append(node4) 44 | node5 = Node() 45 | node5.value = 2 46 | node2.children.append(node5) 47 | node6 = Node() 48 | node6.value = 0 49 | node2.children.append(node6) 50 | # Perform minimax with alpha-beta pruning 51 | result = minimax_alpha_beta(root, 3, -math.inf, math.inf, True) 52 | print("Optimal value:", result) 53 | -------------------------------------------------------------------------------- /Astar.py: -------------------------------------------------------------------------------- 1 | def aStarAlgo(start_node, stop_node): 2 | 3 | open_set = set(start_node) 4 | closed_set = set() 5 | g = {} #store distance from starting node 6 | parents = {}# parents contains an adjacency map of all nodes 7 | 8 | #ditance of starting node from itself is zero 9 | g[start_node] = 0 10 | #start_node is root node i.e it has no parent nodes 11 | #so start_node is set to its own parent node 12 | parents[start_node] = start_node 13 | 14 | 15 | while len(open_set) > 0: 16 | n = None 17 | 18 | #node with lowest f() is found 19 | for v in open_set: 20 | if n == None or g[v] + heuristic(v) < g[n] + heuristic(n): 21 | n = v 22 | 23 | 24 | if n == stop_node or Graph_nodes[n] == None: 25 | pass 26 | else: 27 | for (m, weight) in get_neighbors(n): 28 | #nodes 'm' not in first and last set are added to first 29 | #n is set its parent 30 | if m not in open_set and m not in closed_set: 31 | open_set.add(m) 32 | parents[m] = n 33 | g[m] = g[n] + weight 34 | 35 | 36 | #for each node m,compare its distance from start i.e g(m) to the 37 | #from start through n node 38 | else: 39 | if g[m] > g[n] + weight: 40 | #update g(m) 41 | g[m] = g[n] + weight 42 | #change parent of m to n 43 | parents[m] = n 44 | 45 | #if m in closed set,remove and add to open 46 | if m in closed_set: 47 | closed_set.remove(m) 48 | open_set.add(m) 49 | 50 | if n == None: 51 | print('Path does not exist!') 52 | return None 53 | 54 | # if the current node is the stop_node 55 | # then we begin reconstructin the path from it to the start_node 56 | if n == stop_node: 57 | path = [] 58 | 59 | while parents[n] != n: 60 | path.append(n) 61 | n = parents[n] 62 | 63 | path.append(start_node) 64 | 65 | path.reverse() 66 | 67 | print('Path found: {}'.format(path)) 68 | return path 69 | 70 | 71 | # remove n from the open_list, and add it to closed_list 72 | # because all of his neighbors were inspected 73 | open_set.remove(n) 74 | closed_set.add(n) 75 | 76 | print('Path does not exist!') 77 | return None 78 | 79 | #define fuction to return neighbor and its distance 80 | #from the passed node 81 | def get_neighbors(v): 82 | if v in Graph_nodes: 83 | return Graph_nodes[v] 84 | else: 85 | return None 86 | #for simplicity we ll consider heuristic distances given 87 | #and this function returns heuristic distance for all nodes 88 | def heuristic(n): 89 | H_dist = { 90 | 'A': 11, 91 | 'B': 6, 92 | 'C': 99, 93 | 'D': 1, 94 | 'E': 7, 95 | 'G': 0, 96 | 97 | } 98 | 99 | return H_dist[n] 100 | 101 | #Describe your graph here 102 | Graph_nodes = { 103 | 'A': [('B', 2), ('E', 3)], 104 | 'B': [('C', 1),('G', 9)], 105 | 'C': None, 106 | 'E': [('D', 6)], 107 | 'D': [('G', 1)], 108 | 109 | } 110 | aStarAlgo('A', 'G') 111 | -------------------------------------------------------------------------------- /bfs.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def bfs(graph, start): 4 | visited = set() 5 | queue = deque([start]) 6 | 7 | while queue: 8 | vertex = queue.popleft() 9 | if vertex not in visited: 10 | print(vertex, end=" ") 11 | visited.add(vertex) 12 | queue.extend(graph[vertex] - visited) 13 | graph = { 14 | 'A': {'B', 'C'}, 15 | 'B': {'A', 'D', 'E'}, 16 | 'C': {'A', 'F', 'G'}, 17 | 'D': {'B'}, 18 | 'E': {'B'}, 19 | 'F': {'C'}, 20 | 'G': {'C'} 21 | } 22 | start_vertex = 'A' 23 | print("BFS starting from vertex", start_vertex, ":") 24 | bfs(graph, start_vertex) 25 | -------------------------------------------------------------------------------- /chatbot.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amrutashingankuli682/AI-Lab-Programes/bbc980089515af2343460677e5f868bce4546eaa/chatbot.py -------------------------------------------------------------------------------- /chatbot2.py: -------------------------------------------------------------------------------- 1 | import random 2 | # Dictionary containing responses for different user inputs 3 | responses = { 4 | "hi": ["Hello!", "Hi there!", "Hey!"], 5 | "how are you": ["I'm doing well, thank you!", "I'm great, thanks for asking!"], 6 | "what's your name": ["I'm a chatbot!", "You can call me ChatBot."], 7 | "what do you do": ["I'm here to chat with you!", "I'm a conversational agent."], 8 | "bye": ["Goodbye!", "See you later!", "Bye! Have a great day!"], 9 | "tell me a joke": ["Why don't scientists trust atoms? Because they make up everything!", "I'm not good at jokes, but here's one: Why was the math book sad? Because it had too many problems."], 10 | "who created you": ["I was created by a team of developers.", "My creators prefer to remain anonymous."], 11 | "what is the weather today": ["I'm sorry, I can't provide real-time information.", "You can check the weather on a weather website or app."], 12 | "how old are you": ["I don't have an age. I'm just a program!", "I exist in the realm of ones and zeros, so I don't age."], 13 | "what is the meaning of life": ["The meaning of life is a philosophical question that has puzzled humans for centuries.", "I think the meaning of life is subjective and varies from person to person."] 14 | } 15 | 16 | # Function to get response from the bot 17 | def get_response(user_input): 18 | if user_input.lower() in responses: 19 | return random.choice(responses[user_input.lower()]) 20 | else: 21 | return "I'm sorry, I don't understand that." 22 | 23 | # Main function to run the chatbot 24 | def main(): 25 | print("Welcome to the ChatBot!") 26 | print("You can start chatting. Type 'bye' to exit.") 27 | while True: 28 | user_input = input("You: ") 29 | if user_input.lower() == 'bye': 30 | print(get_response(user_input)) 31 | break 32 | else: 33 | print("ChatBot:", get_response(user_input)) 34 | 35 | if __name__ == "__main__": 36 | main() 37 | 38 | -------------------------------------------------------------------------------- /dfs.py: -------------------------------------------------------------------------------- 1 | def dfs(graph, start, visited=None): 2 | if visited is None: 3 | visited = set() 4 | 5 | print(start, end=" ") 6 | visited.add(start) 7 | 8 | for neighbor in graph[start] - visited: 9 | dfs(graph, neighbor, visited) 10 | 11 | graph = { 12 | 'A': {'B', 'C'}, 13 | 'B': {'A', 'D', 'E'}, 14 | 'C': {'A', 'F', 'G'}, 15 | 'D': {'B'}, 16 | 'E': {'B'}, 17 | 'F': {'C'}, 18 | 'G': {'C'} 19 | } 20 | start_vertex = 'A' 21 | print("DFS starting from vertex", start_vertex, ":") 22 | dfs(graph, start_vertex) 23 | -------------------------------------------------------------------------------- /fuzzy.py: -------------------------------------------------------------------------------- 1 | def fuzzy_union(set1, set2): 2 | union_set = {} 3 | for element in set1: 4 | union_set[element] = max(set1[element], set2.get(element, 0)) 5 | for element in set2: 6 | if element not in union_set: 7 | union_set[element] = set2[element] 8 | return union_set 9 | 10 | def fuzzy_intersection(set1, set2): 11 | intersection_set = {} 12 | for element in set1: 13 | if element in set2: 14 | intersection_set[element] = min(set1[element], set2[element]) 15 | return intersection_set 16 | 17 | def display_fuzzy_set(fuzzy_set): 18 | print("{", end="") 19 | for element, membership in fuzzy_set.items(): 20 | print(f"{element}: {membership}", end=", ") 21 | print("}") 22 | 23 | # Example fuzzy sets 24 | set1 = {'a': 0.8, 'b': 0.6, 'c': 0.4, 'd': 0.2, 'e': 0.1} 25 | set2 = {'a': 0.7, 'b': 0.5, 'c': 0.3, 'f': 0.9, 'g': 0.4} 26 | 27 | print("Fuzzy set 1:") 28 | display_fuzzy_set(set1) 29 | 30 | print("\nFuzzy set 2:") 31 | display_fuzzy_set(set2) 32 | 33 | print("\nUnion of the fuzzy sets:") 34 | union_set = fuzzy_union(set1, set2) 35 | display_fuzzy_set(union_set) 36 | 37 | print("\nIntersection of the fuzzy sets:") 38 | intersection_set = fuzzy_intersection(set1, set2) 39 | display_fuzzy_set(intersection_set) 40 | -------------------------------------------------------------------------------- /nim_game.py: -------------------------------------------------------------------------------- 1 | def print_board(heap): 2 | print(f"Current heap: {'|' * heap}") 3 | 4 | def get_user_move(heap): 5 | while True: 6 | try: 7 | sticks_to_remove = int(input(f"Enter the number of sticks to remove (minimum 1, maximum {min(heap, heap // 2)}): ")) 8 | if 1 <= sticks_to_remove <= min(heap, heap // 2): 9 | break 10 | else: 11 | print(f"Invalid number of sticks. Please enter a number between 1 and {min(heap, heap // 2)}.") 12 | except ValueError: 13 | print("Invalid input. Please enter a valid number.") 14 | 15 | return sticks_to_remove 16 | 17 | def get_computer_move(heap): 18 | xor_sum = heap 19 | for i in range(heap): 20 | xor_sum ^= i 21 | 22 | if xor_sum == 0: 23 | max_sticks = min(heap, heap // 2) 24 | sticks_to_remove = random.randint(1, max_sticks) 25 | else: 26 | max_sticks = min(heap // 2, heap) 27 | sticks_to_remove = max(1, min(max_sticks, heap - xor_sum)) 28 | 29 | return sticks_to_remove 30 | 31 | def nim_game(): 32 | heap = 16 33 | player_turn = 1 34 | 35 | while heap > 1: 36 | print_board(heap) 37 | 38 | if player_turn == 1: 39 | player_name = "Player 1" 40 | sticks_to_remove = get_user_move(heap) 41 | else: 42 | player_name = "Computer" 43 | sticks_to_remove = get_computer_move(heap) 44 | 45 | heap -= sticks_to_remove 46 | print(f"{player_name} removes {sticks_to_remove} sticks.") 47 | 48 | player_turn = 3 - player_turn # Switch player (1 -> 2, 2 -> 1) 49 | 50 | print_board(heap) 51 | winner = "Player 1" if player_turn == 2 else "Computer" 52 | print(f"Player {player_turn} picks the last stick ") 53 | print(f"\n{winner} is the winner!") 54 | 55 | if __name__ == "__main__": 56 | import random 57 | nim_game() 58 | -------------------------------------------------------------------------------- /tic tac toe.py: -------------------------------------------------------------------------------- 1 | board=["-","-","-", 2 | "-","-","-", 3 | "-","-","-"] 4 | def print_board(): 5 | print(board[0]+" | "+board[1]+" | "+board[2]) 6 | print(board[3]+" | "+board[4]+" | "+board[5]) 7 | print(board[6]+" | "+board[7]+" | "+board[8]) 8 | def print_turn(player): 9 | print(player+"'s turn") 10 | position=input("enter position from 1-9:") 11 | while position not in ["1","2","3","4","5","6","7","8","9"]: 12 | print("invalid choice(1-9)") 13 | position=int(position)-1 14 | while board[position] != "-": 15 | position=int(input("position already taken :")) 16 | board[position]=player 17 | print_board() 18 | def check_game_over(): 19 | if (board[0] == board[1] == board[2] !="-") or \ 20 | (board[3] == board[4] == board[5] !="-") or \ 21 | (board[6] == board[7] == board[8] !="-") or \ 22 | (board[0] == board[3] == board[6] != "-") or \ 23 | (board[1] == board[4] == board[7] != "-") or \ 24 | (board[2] == board[5] == board[8] != "-") or \ 25 | (board[0] == board[4] == board[8] != "-") or \ 26 | (board[2] == board[4] == board[6] != "-"): 27 | return "win" 28 | elif "-" not in board: 29 | return "tie" 30 | else: 31 | return "play" 32 | def play_game(): 33 | print_board() 34 | current_player="X" 35 | game_over = False 36 | while not game_over: 37 | print_turn(current_player) 38 | game_result = check_game_over() 39 | if game_result == "win": 40 | print(current_player + " wins!") 41 | game_over = True 42 | elif game_result == "tie": 43 | print("It's a tie!") 44 | game_over = True 45 | else: 46 | current_player = "O" if current_player == "X" else "X" 47 | play_game() -------------------------------------------------------------------------------- /tsp.py: -------------------------------------------------------------------------------- 1 | from scipy.spatial import distance 2 | import numpy as np 3 | 4 | def nearest_neighbor_algorithm(distance_matrix, start_city=0): 5 | num_cities = len(distance_matrix) 6 | unvisited_cities = set(range(num_cities)) 7 | tour = [start_city] 8 | current_city = start_city 9 | 10 | while unvisited_cities: 11 | nearest_city = min(unvisited_cities, key=lambda city: distance_matrix[current_city, city]) 12 | tour.append(nearest_city) 13 | unvisited_cities.remove(nearest_city) 14 | current_city = nearest_city 15 | 16 | tour.append(start_city) 17 | return tour 18 | 19 | # Example usage: 20 | # Define the coordinates of cities 21 | cities_coordinates = np.array([ 22 | [0, 0], 23 | [1, 2], 24 | [3, 1], 25 | [5, 2] 26 | ]) 27 | 28 | # Calculate the distance matrix 29 | distance_matrix = distance.cdist(cities_coordinates, cities_coordinates) 30 | 31 | # Solve TSP using nearest neighbor algorithm 32 | start_city = 0 33 | tour = nearest_neighbor_algorithm(distance_matrix, start_city) 34 | 35 | # Print the result 36 | print("Optimal Tour:", tour) 37 | --------------------------------------------------------------------------------