├── A star ├── Alpha-Beta Pruning ├── ChatBot ├── Fuzzy Logic ├── NIM game └── Tic_Tac_Toe /A star: -------------------------------------------------------------------------------- 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 | #distance 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 | -------------------------------------------------------------------------------- /Alpha-Beta Pruning: -------------------------------------------------------------------------------- 1 | MAX, MIN = 1000, -1000 2 | 3 | def minimax(depth, nodeIndex, maximizingPlayer, 4 | values, alpha, beta): 5 | 6 | if depth == 3: 7 | return values[nodeIndex] 8 | 9 | if maximizingPlayer: 10 | 11 | best = MIN 12 | 13 | for i in range(0, 2): 14 | val = minimax(depth + 1, nodeIndex * 2 + i, False, values, alpha, beta) 15 | best = max(best, val) 16 | alpha = max(alpha, best) 17 | 18 | # Alpha Beta Pruning 19 | if beta <= alpha: 20 | break 21 | 22 | return best 23 | 24 | else: 25 | best = MAX 26 | 27 | for i in range(0, 2): 28 | val = minimax(depth + 1, nodeIndex * 2 + i, True, values, alpha, beta) 29 | best = min(best, val) 30 | beta = min(beta, best) 31 | 32 | # Alpha Beta Pruning 33 | if beta <= alpha: 34 | break 35 | 36 | return best 37 | 38 | # Driver Code 39 | if __name__ == "__main__": 40 | 41 | values = [10,9,14,18,5,4,50,3] 42 | print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX)) 43 | -------------------------------------------------------------------------------- /ChatBot: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Fuzzy Logic: -------------------------------------------------------------------------------- 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: -------------------------------------------------------------------------------- 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: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def print_board(board): 4 | print(" 1 2 3") 5 | for i in range(3): 6 | print(f"{i+1} {' '.join(board[i])}") 7 | 8 | def check_winner(board, player): 9 | # Check for row wins 10 | for row in board: 11 | if all(cell == player for cell in row): 12 | return True 13 | # Check for column wins 14 | for col in range(3): 15 | if all(board[row][col] == player for row in range(3)): 16 | return True 17 | # Check for diagonal wins 18 | if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)): 19 | return True 20 | return False 21 | 22 | def is_board_full(board): 23 | return all(cell != ' ' for row in board for cell in row) 24 | 25 | def get_available_moves(board): 26 | return [(i, j) for i in range(3) for j in range(3) if board[i][j] == ' '] 27 | 28 | def player_move(board): 29 | while True: 30 | try: 31 | row, col = map(int, input("Enter your move (row and column, e.g., 1 2): ").split()) 32 | if 1 <= row <= 3 and 1 <= col <= 3 and board[row - 1][col - 1] == ' ': 33 | return row - 1, col - 1 34 | else: 35 | print("Invalid move. Try again.") 36 | except ValueError: 37 | print("Invalid input. Please enter two integers separated by a space.") 38 | 39 | def computer_move(board, computer, player): 40 | available_moves = get_available_moves(board) 41 | 42 | # Try to win 43 | for move in available_moves: 44 | board[move[0]][move[1]] = computer 45 | if check_winner(board, computer): 46 | return move 47 | board[move[0]][move[1]] = ' ' # Undo move 48 | 49 | # Block player from winning 50 | for move in available_moves: 51 | board[move[0]][move[1]] = player 52 | if check_winner(board, player): 53 | board[move[0]][move[1]] = computer 54 | return move 55 | board[move[0]][move[1]] = ' ' # Undo move 56 | 57 | # Otherwise, make a random move 58 | return random.choice(available_moves) 59 | 60 | def play_game(): 61 | #Creating a 2D array board with string value ' ' in it. 62 | board = [[' ' for i in range(3)] for j in range(3)] 63 | 64 | #board = [[ , , ] 65 | # [ , , ] 66 | # [ , , ]] 67 | 68 | player = 'X' 69 | computer = 'O' 70 | 71 | while True: 72 | print_board(board) #initial board 73 | 74 | if check_winner(board, player): 75 | print("Congratulations! You win!") 76 | break 77 | elif check_winner(board, computer): 78 | print("Computer wins!") 79 | break 80 | elif is_board_full(board): 81 | print("It's a tie!") 82 | break 83 | 84 | if player == 'X': 85 | row, col = player_move(board) 86 | board[row][col] = 'X' 87 | player = 'O' 88 | computer = 'X' 89 | else: 90 | row, col = computer_move(board, computer, player) 91 | board[row][col] = 'O' 92 | player = 'X' 93 | computer = 'O' 94 | 95 | if __name__ == "__main__": 96 | play_game() 97 | --------------------------------------------------------------------------------