0% found this document useful (0 votes)
13 views26 pages

Artificial Intelligence Lab experiments (alex)

The document outlines a series of programming experiments for a BCA course at G D Goenka University, detailing various tasks such as counting elements in a list, solving the Water-Jug problem, and implementing games like Tic-Tac-Toe and Hangman. Each experiment includes specific aims, example code, and expected outputs. The document serves as a practical guide for students to enhance their programming skills in Python.

Uploaded by

alwinstephen22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views26 pages

Artificial Intelligence Lab experiments (alex)

The document outlines a series of programming experiments for a BCA course at G D Goenka University, detailing various tasks such as counting elements in a list, solving the Water-Jug problem, and implementing games like Tic-Tac-Toe and Hangman. Each experiment includes specific aims, example code, and expected outputs. The document serves as a practical guide for students to enhance their programming skills in Python.

Uploaded by

alwinstephen22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Artificial Intelligence Lab

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

a. Write a program to count number of elements in a


list.
1. b. Write a program to reverse the list. 12 Sep 2024
c. Write a program to append, replace and delete an
integer from the list.

2. Write a program to solve Water-Jug problem. 19 Sep 2024

3. Write a program to solve 8-tiles puzzle problem. 26 Sep 2024

Write a program to solve Shortest path problem:


4. i. Using BFS. 03 Oct 2024
ii. Using Lowest-cost-first search.
Write a program to implement TIC - TAC - TOE
5. game (Understanding Minimax Algorithm and 10 Oct 2024
Alpha - Beta pruning)
Write a program to implement Hangman game (Or
6. 24 Oct 2024
Wordle)

Write a program to implement Travelling salesman


7. 07 Nov 2024
problem using python.

Write a program to implement Monkey Banana


8. 14 Nov 2024
problem using python.
Experiment – 1
Aim: a. Write a program to count number of elements in a list.
b. Write a program to reverse the list.
c. Write a program to append, replace and delete an integer from the list.

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:

b. Reversing the list.


def reverse_list(lst):
return lst[::-1]

# 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

def replace_in_list(lst, old_element, new_element):


if old_element in lst:
index = lst.index(old_element)
lst[index] = new_element
return lst

def delete_from_list(lst, element):


if element in lst:
lst.remove(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

def water_jug_problem(capacity_a, capacity_b, target):


# Check if the goal is achievable
if target > max(capacity_a, capacity_b) or target % gcd(capacity_a,
capacity_b) != 0:
return "Not possible to measure the desired amount"

visited = set()
queue = deque()

# Initial state: (amount in jug A, amount in jug B)


queue.append((0, 0)) # Start with both jugs empty
visited.add((0, 0))

while queue:
a, b = queue.popleft()

# Check if we have reached the goal


if a == target or b == target or a + b == target:
return f"Reached: Jug A = {a}, Jug B = {b}"

# 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
]

for state in possible_states:


if state not in visited:
visited.add(state)
queue.append(state)

return "No solution found"

def gcd(a, b):


while b:
a, b = b, a % b
return 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

for dx, dy in directions:


new_x, new_y = x + dx, y + dy
if 0 <= new_x < self.size and 0 <= new_y < self.size:
new_board = self.board[:]
new_empty_tile_pos = (new_x, new_y)
new_index = new_x * self.size + new_y
old_index = x * self.size + y
# Swap the empty tile with the adjacent tile
new_board[old_index], new_board[new_index] =
new_board[new_index], new_board[old_index]
neighbors.append(PuzzleState(new_board, new_empty_tile_pos,
self.moves + 1, self))
return neighbors

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 __lt__(self, other):


return (self.moves + self.heuristic()) < (other.moves +
other.heuristic())

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))

for neighbor in current_state.get_neighbors():


if tuple(neighbor.board) not in visited:
heapq.heappush(priority_queue, neighbor)

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

def bfs_shortest_path(graph, start, goal):


queue = deque([(start, [start])]) # Stores (node, path) tuples
visited = set()

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)

for neighbor in graph[current_node]:


if neighbor not in visited:
queue.append((neighbor, path + [neighbor]))
visited.add(neighbor)

return None # Return None if no path is found

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:

ii. Lowest-cost-first search (Dijkstra’s algorithm)


import heapq

def dijkstra_shortest_path(graph, start, goal):


priority_queue = [(0, start)] # (cost, node)
distances = {node: float('infinity') for node in graph}
distances[start] = 0
previous_nodes = {node: None for node in graph}

while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)

if current_distance > distances[current_node]:


continue

if current_node == goal:
break

for neighbor, weight in graph[current_node].items():


distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
previous_nodes[neighbor] = current_node
heapq.heappush(priority_queue, (distance, neighbor))

# Reconstruct the shortest path


path = []
current_node = goal
while current_node is not None:
path.append(current_node)
current_node = previous_nodes[current_node]
path.reverse()

return path if path[0] == start else None

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

# Constants for the game


PLAYER_X = 'X'
PLAYER_O = 'O'
EMPTY = ' '

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_winner(self, player):


# Check rows, columns, and diagonals for a win
for row in range(3):
if all([self.board[row][col] == player for col in range(3)]):
return True
for col in range(3):
if all([self.board[row][col] == player for row in range(3)]):
return True
if all([self.board[i][i] == player for i in range(3)]) or
all([self.board[i][2 - i] == player for i in range(3)]):
return True
return False

def is_draw(self):
return all([self.board[row][col] != EMPTY for row in range(3) for col in
range(3)])

def minimax(self, depth, alpha, beta, is_maximizing):


if self.is_winner(PLAYER_O):
return 10 - depth
if self.is_winner(PLAYER_X):
return depth - 10
if self.is_draw():
return 0

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

self.current_player = PLAYER_X if self.current_player == PLAYER_O


else PLAYER_O

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]

def guess(self, letter):


if letter in self.guessed_letters:
print(f"You've already guessed '{letter}'. Try another letter.")
return False

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 calculate_total_distance(distance_matrix, path):


total_distance = 0
for i in range(len(path) - 1):
total_distance += distance_matrix[path[i]][path[i + 1]]
total_distance += distance_matrix[path[-1]][path[0]] # Returning to the
start city
return total_distance

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

# Check the total distance for each path


for path in all_paths:
total_distance = calculate_total_distance(distance_matrix, path)
if total_distance < min_distance:
min_distance = total_distance
best_path = path

return best_path, min_distance

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]
]

best_path, min_distance = travelling_salesman_brute_force(distance_matrix)

print("Optimal path:", best_path)


print("Minimum distance:", min_distance)

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)")

while not game.is_banana_reachable():


action = input("Enter action (move/jump/use_box): ").lower()
game.perform_action(action)

print("The monkey has successfully reached the banana!")

if __name__ == "__main__":
main()

Output:

You might also like