Artificial Intelligence Lab experiments (alex)
Artificial Intelligence Lab experiments (alex)
CAP3004L
School of Engineering and Sciences
Department of Computer Science and Engineering
Submitted By:
Student Name Alex Yogesh
Roll No. 220160212007
Programme BCA
Section & Group A-T1
Department Computer Science and Engineering
Year / Semester 3rd Year / 5th Semester
Submitted To:
Faculty Name Mr. Daksh
G D Goenka University
Gurgaon, Haryana
INDEX
S. No. AIM OF THE EXPERIMENTS DATE SIGNATURE
Input:
a. Counting the number of elements in a list.
def count_elements(lst):
count = 0
for _ in lst:
count += 1
return count
# Example usage:
my_list = [10, 20, 30, 40, 50]
print("Number of elements in the list:", count_elements(my_list))
Output:
# Example usage:
my_list = [10, 20, 30, 40, 50]
print("Reversed list:", reverse_list(my_list))
Output:
c. Appending, replacing, and deleting an integer from the list.
def append_to_list(lst, element):
lst.append(element)
return lst
# Example usage:
my_list = [10, 20, 30, 40, 50]
# Append an element
my_list = append_to_list(my_list, 60)
print("After appending 60:", my_list)
# Replace an element
my_list = replace_in_list(my_list, 30, 35)
print("After replacing 30 with 35:", my_list)
# Delete an element
my_list = delete_from_list(my_list, 40)
print("After deleting 40:", my_list)
Output:
Experiment – 2
Aim: Write a program to solve Water-Jug problem.
Input:
from collections import deque
visited = set()
queue = deque()
while queue:
a, b = queue.popleft()
# Possible actions
possible_states = [
(capacity_a, b), # Fill Jug A
(a, capacity_b), # Fill Jug B
(0, b), # Empty Jug A
(a, 0), # Empty Jug B
(a - min(a, capacity_b - b), b + min(a, capacity_b - b)), # Pour A
into B
(a + min(b, capacity_a - a), b - min(b, capacity_a - a)), # Pour B
into A
]
# Example usage:
capacity_a = 5 # Capacity of jug A
capacity_b = 3 # Capacity of jug B
target = 4 # Desired amount
result = water_jug_problem(capacity_a, capacity_b, target)
print(result)
Output:
Experiment – 3
Aim: Write a program to solve 8-tiles puzzle problem.
Input:
import heapq
class PuzzleState:
def __init__(self, board, empty_tile_pos, moves=0, previous=None):
self.board = board
self.empty_tile_pos = empty_tile_pos
self.moves = moves
self.previous = previous
self.size = 3 # 3x3 grid
def is_goal(self):
return self.board == [1, 2, 3, 4, 5, 6, 7, 8, 0]
def get_neighbors(self):
neighbors = []
x, y = self.empty_tile_pos
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Right, Down, Left, Up
def heuristic(self):
# Manhattan distance heuristic
distance = 0
for i in range(len(self.board)):
if self.board[i] != 0: # Skip the empty tile
target_x = (self.board[i] - 1) // self.size
target_y = (self.board[i] - 1) % self.size
current_x = i // self.size
current_y = i % self.size
distance += abs(target_x - current_x) + abs(target_y - current_y)
return distance
def a_star(initial_board):
initial_empty_tile_pos = (initial_board.index(0) // 3, initial_board.index(0)
% 3)
initial_state = PuzzleState(initial_board, initial_empty_tile_pos)
priority_queue = []
heapq.heappush(priority_queue, initial_state)
visited = set()
while priority_queue:
current_state = heapq.heappop(priority_queue)
if current_state.is_goal():
return current_state
visited.add(tuple(current_state.board))
return None
def print_solution(solution):
moves = []
while solution:
moves.append(solution.board)
solution = solution.previous
for move in reversed(moves):
print(move)
def main():
# Example initial board configuration
initial_board = [1, 2, 3, 4, 5, 6, 0, 7, 8] # 0 represents the empty space
solution = a_star(initial_board)
if solution:
print("Solution found:")
print_solution(solution)
else:
print("No solution exists for the given board configuration.")
if __name__ == "__main__":
main()
Output:
Experiment – 4
Aim: Write a program to solve Shortest path problem:
i. Using BFS.
ii. Using Lowest-cost-first search.
Input:
i. BFS (Breadth-First Search)
from collections import deque
while queue:
current_node, path = queue.popleft()
if current_node == goal:
return path # Return the path once the goal is found
visited.add(current_node)
def main():
# Example graph as an adjacency list
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
start = 'A'
goal = 'F'
path = bfs_shortest_path(graph, start, goal)
if path:
print(f"Shortest path from {start} to {goal}: {path}")
else:
print("No path found.")
if __name__ == "__main__":
main()
Output:
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
if current_node == goal:
break
def main():
# Example graph as an adjacency list with weights
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'D': 2, 'E': 5},
'C': {'A': 4, 'F': 1},
'D': {'B': 2},
'E': {'B': 5, 'F': 3},
'F': {'C': 1, 'E': 3}
}
start = 'A'
goal = 'F'
path = dijkstra_shortest_path(graph, start, goal)
if path:
print(f"Shortest path from {start} to {goal}: {path}")
else:
print("No path found.")
if __name__ == "__main__":
main()
Output:
Experiment – 5
Aim: Write a program to implement TIC - TAC - TOE game (Understanding
Minimax Algorithm and Alpha - Beta pruning)
Input:
import math
class TicTacToe:
def __init__(self):
self.board = [[EMPTY] * 3 for _ in range(3)]
self.current_player = PLAYER_X
def print_board(self):
for row in self.board:
print('|'.join(row))
print('-' * 5)
def is_draw(self):
return all([self.board[row][col] != EMPTY for row in range(3) for col in
range(3)])
if is_maximizing:
max_eval = -math.inf
for row in range(3):
for col in range(3):
if self.board[row][col] == EMPTY:
self.board[row][col] = PLAYER_O
evaluation = self.minimax(depth + 1, alpha, beta, False)
self.board[row][col] = EMPTY
max_eval = max(max_eval, evaluation)
alpha = max(alpha, evaluation)
if beta <= alpha:
break
return max_eval
else:
min_eval = math.inf
for row in range(3):
for col in range(3):
if self.board[row][col] == EMPTY:
self.board[row][col] = PLAYER_X
evaluation = self.minimax(depth + 1, alpha, beta, True)
self.board[row][col] = EMPTY
min_eval = min(min_eval, evaluation)
beta = min(beta, evaluation)
if beta <= alpha:
break
return min_eval
def best_move(self):
best_score = -math.inf
move = (-1, -1)
for row in range(3):
for col in range(3):
if self.board[row][col] == EMPTY:
self.board[row][col] = PLAYER_O
score = self.minimax(0, -math.inf, math.inf, False)
self.board[row][col] = EMPTY
if score > best_score:
best_score = score
move = (row, col)
return move
def play(self):
while True:
self.print_board()
if self.current_player == PLAYER_X:
row = int(input("Enter row (0, 1, 2): "))
col = int(input("Enter column (0, 1, 2): "))
if self.board[row][col] == EMPTY:
self.board[row][col] = PLAYER_X
if self.is_winner(PLAYER_X):
self.print_board()
print("Player X wins!")
return
else:
print("Invalid move, try again.")
continue
else:
row, col = self.best_move()
self.board[row][col] = PLAYER_O
print(f"Computer plays at {row}, {col}")
if self.is_winner(PLAYER_O):
self.print_board()
print("Player O (Computer) wins!")
return
if self.is_draw():
self.print_board()
print("It's a draw!")
return
def main():
game = TicTacToe()
game.play()
if __name__ == "__main__":
main()
Output:
Experiment – 6
Aim: Write a program to implement Hangman game (Or Wordle)
Input:
import random
class Hangman:
def __init__(self, word_list, max_attempts=6):
self.word_list = word_list
self.max_attempts = max_attempts
self.secret_word = random.choice(self.word_list).upper()
self.attempts = 0
self.guessed_letters = set()
self.correct_positions = ['_'] * len(self.secret_word)
def display_status(self):
print("\n" + self.get_hangman_visual())
print("Current word: " + ' '.join(self.correct_positions))
print(f"Guessed letters: {', '.join(sorted(self.guessed_letters))}")
print(f"Attempts remaining: {self.max_attempts - self.attempts}")
def get_hangman_visual(self):
stages = [
"""
-----
| |
| O
| /|\\
| / \\
|
""",
"""
-----
| |
| O
| /|\\
| /
|
""",
"""
-----
| |
| O
| /|
|
|
""",
"""
-----
| |
| O
| |
|
|
""",
"""
-----
| |
| O
|
|
|
""",
"""
-----
| |
|
|
|
|
""",
"""
-----
| |
| |
| |
|
|
"""
]
return stages[self.attempts]
self.guessed_letters.add(letter)
if letter in self.secret_word:
print(f"Good guess! '{letter}' is in the word.")
for index, char in enumerate(self.secret_word):
if char == letter:
self.correct_positions[index] = letter
return True
else:
self.attempts += 1
print(f"Sorry, '{letter}' is not in the word.")
return False
def is_won(self):
return '_' not in self.correct_positions
def is_lost(self):
return self.attempts >= self.max_attempts
def main():
word_list = ["python", "java", "kotlin", "javascript", "hangman"]
game = Hangman(word_list)
print("Welcome to Hangman!")
while not game.is_won() and not game.is_lost():
game.display_status()
guess = input("Enter a letter: ").upper()
if len(guess) == 1 and guess.isalpha():
game.guess(guess)
else:
print("Please enter a single alphabetical character.")
if game.is_won():
print(f"Congratulations! You've guessed the word: {game.secret_word}")
else:
print(game.get_hangman_visual())
print(f"Sorry, you've run out of attempts. The word was:
{game.secret_word}")
if __name__ == "__main__":
main()
Output:
Experiment – 7
Aim: Write a program to implement Travelling salesman problem using python.
Input:
import itertools
def travelling_salesman_brute_force(distance_matrix):
n = len(distance_matrix)
cities = list(range(n))
# Generate all possible paths (permutations of cities)
all_paths = itertools.permutations(cities)
min_distance = float('inf')
best_path = None
def main():
# Example distance matrix (symmetric, distance from city i to city j)
# For example, city 0 to city 1 has a distance of 10, and so on
distance_matrix = [
[0, 10, 15, 20, 25],
[10, 0, 35, 25, 30],
[15, 35, 0, 30, 5],
[20, 25, 30, 0, 15],
[25, 30, 5, 15, 0]
]
if __name__ == "__main__":
main()
Output:
Experiment – 8
Aim: Write a program to implement Monkey Banana problem using python.
Input:
class MonkeyBanana:
def __init__(self):
self.monkey_position = 0 # Monkey's position (0: ground, 1: on box)
self.banana_position = 2 # Banana's position (out of reach, requires
box)
self.box_position = 1 # Box position (can be moved to help the monkey)
self.actions = ["move", "jump", "use_box"]
def is_banana_reachable(self):
return self.monkey_position == self.banana_position
def move_monkey(self):
if self.monkey_position == self.box_position:
print("Monkey is on the box and can now reach the banana.")
self.monkey_position = self.box_position # Monkey stays on the box
else:
print("Monkey is moving towards the box.")
self.monkey_position = self.box_position # Move the monkey to the
box
def jump(self):
if self.monkey_position == self.box_position:
print("Monkey is jumping towards the banana!")
self.monkey_position = self.banana_position # Jump directly to the
banana
else:
print("Monkey jumps but can't reach the banana from the ground.")
def use_box(self):
if self.monkey_position == self.box_position:
print("Monkey is using the box to get the banana!")
self.monkey_position = self.banana_position # The box helps the
monkey reach the banana
else:
print("Monkey uses the box but isn't close enough to the banana
yet.")
def perform_action(self, action):
if action == "move":
self.move_monkey()
elif action == "jump":
self.jump()
elif action == "use_box":
self.use_box()
else:
print("Invalid action!")
def main():
game = MonkeyBanana()
print("Monkey's initial position: Ground level (0), Box position (1), Banana
position (2)")
if __name__ == "__main__":
main()
Output: