My
Here’s the full content from your file excluding the parts where "Name", "Class", or "Roll No" appear:
Assignment 1
Problem statement:
Given two jugs with specific capacities, determine the sequence of operations required to measure a specific amount of water in one of the jugs. The operations allowed are:
-
Fill either jug to its maximum capacity.
-
Empty either jug completely.
-
Pour water from one jug into the other until one is empty or the other is full.
INPUT:
def WaterJug(jugA, jugB, goal):
stack = []
visited = set()
stack.append((0, 0))
while stack:
current_state = stack.pop()
x, y = current_state
print(f"Current state: ({x}, {y})")
if (x == goal and y == 0) or (y == goal and x == 0):
print(f"Last state: ({x}, {y})")
return True
if current_state in visited:
continue
visited.add(current_state)
states = set()
states.add((jugA, y))
states.add((x, jugB))
states.add((0, y))
states.add((x, 0))
pour_AtoB = min(x, jugB - y)
states.add((x - pour_AtoB, y + pour_AtoB))
pour_BtoA = min(y, jugA - x)
states.add((x + pour_BtoA, y - pour_BtoA))
for state in states:
if state not in visited:
stack.append(state)
return False
jugA = int(input("Enter the capacity of jug A: "))
jugB = int(input("Enter the capacity of jug B: "))
goal = int(input("Enter the goal amount: "))
if WaterJug(jugA, jugB, goal):
print("Solution found!")
else:
print("Solution not found.")
Assignment 2
Problem statement:
Given a 3×3 grid containing eight numbered tiles (1–8) and one empty space, develop a program to find the optimal sequence of moves that transforms an initial configuration into the goal state. A tile can only be moved up, down, left, or right if the adjacent tile is empty.
INPUT
def print_puzzle(puzzle):
for i in range(9):
if i % 3 == 0 and i > 0:
print("")
print(str(puzzle[i]) + " ", end="")
print("")
def calculate_heuristic(state, goal_state):
heuristic = 0
for i in range(9):
if state[i] != 0 and state[i] != goal_state[i]:
heuristic += 1
return heuristic
def find_best_move(possible_moves, zero_position, current_state, goal_state):
min_heuristic = float('inf')
best_state = current_state.copy()
for move in possible_moves:
temp_state = current_state.copy()
temp_state[zero_position], temp_state[move] = temp_state[move], temp_state[zero_position]
current_heuristic = calculate_heuristic(temp_state, goal_state)
if current_heuristic < min_heuristic:
min_heuristic = current_heuristic
best_state = temp_state.copy()
return best_state, min_heuristic
def get_puzzle_state(prompt):
while True:
try:
state = list(map(int, input(prompt).split()))
if len(state) == 9 and set(state) == set(range(9)):
return state
else:
print("Invalid input. Please enter 9 unique numbers (0-8).")
except ValueError:
print("Invalid input. Please enter numbers only.")
def main():
print("8-Puzzle Solver")
print("Enter the puzzle states as 9 space-separated integers (0-8), where 0 represents the blank tile.")
initial_state = get_puzzle_state("Enter the initial state: ")
goal_state = get_puzzle_state("Enter the goal state: ")
heuristic_value = calculate_heuristic(initial_state, goal_state)
level = 1
print(f"\n------ Level {level} ------")
print_puzzle(initial_state)
print(f"Misplaced Tiles: {heuristic_value}")
current_state = initial_state
while heuristic_value > 0:
zero_position = current_state.index(0)
level += 1
if zero_position == 0:
possible_moves = [1, 3]
elif zero_position == 1:
possible_moves = [0, 2, 4]
elif zero_position == 2:
possible_moves = [1, 5]
elif zero_position == 3:
possible_moves = [0, 4, 6]
elif zero_position == 4:
possible_moves = [1, 3, 5, 7]
elif zero_position == 5:
possible_moves = [2, 4, 8]
elif zero_position == 6:
possible_moves = [3, 7]
elif zero_position == 7:
possible_moves = [4, 6, 8]
elif zero_position == 8:
possible_moves = [5, 7]
current_state, heuristic_value = find_best_move(possible_moves, zero_position, current_state, goal_state)
print(f"\n------ Level {level} ------")
print_puzzle(current_state)
print(f"Misplaced Tiles: {heuristic_value}")
print("\nPuzzle solved!")
if name == "main":
main()
(There are several more Assignments: 3, 4, 5, 6, 7, and a Mini Project.)
The document is very long.
Would you like me to continue copying the remaining content the same way? (Assignments 3 onwards.)
It will take a few more messages.
Shall I continue?
Got it — you want everything except:
Name, Class, Roll No (already excluded)
Mini Project (i.e., skip the Black & White Image Converter part)
I'll now continue copying only the Assignments 3, 4, 5, 6, and 7 exactly as they are.
Assignment 3
Problem statement:
Implement Greedy Strategy using Dijkstra’s algorithm to find the shortest path.
INPUT
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
visited = set()
while len(visited) < len(graph):
current_node = None
current_distance = float('inf')
for node in graph:
if node not in visited and distances[node] < current_distance:
current_distance = distances[node]
current_node = node
if current_node is None:
break
visited.add(current_node)
for neighbor, weight in graph[current_node]:
if neighbor not in visited:
new_distance = current_distance + weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
return distances
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
start_node = 'A'
shortest_paths = dijkstra(graph, start_node)
print(f"Shortest distances from {start_node}:")
for node, distance in shortest_paths.items():
print(f"{node}: {distance}")
Assignment 4
Problem statement:
Implement a Python program to solve the Tic-Tac-Toe game using the Min-Max algorithm.
INPUT
import random
board = [i for i in range(1, 10)]
PLAYER = 'X'
COMPUTER = 'O'
EMPTY = ' '
winners = ((0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6))
def print_board():
for i in range(3):
print(" | ".join(str(board[j]) if board[j] == j + 1 else board[j] for j in range(i * 3, i * 3 + 3)))
if i < 2:
print("---------")
def check_win(brd, player):
for tup in winners:
if all(brd[ix] == player for ix in tup):
return True
return False
def available_moves(brd):
return [i for i in range(9) if brd[i] == i + 1]
def minimax(brd, depth, is_maximizing):
if check_win(brd, COMPUTER):
return 1
if check_win(brd, PLAYER):
return -1
if not available_moves(brd):
return 0
if is_maximizing:
best_score = -float('inf')
for move in available_moves(brd):
brd[move] = COMPUTER
score = minimax(brd, depth + 1, False)
brd[move] = move + 1
best_score = max(score, best_score)
return best_score
else:
best_score = float('inf')
for move in available_moves(brd):
brd[move] = PLAYER
score = minimax(brd, depth + 1, True)
brd[move] = move + 1
best_score = min(score, best_score)
return best_score
def top_move(brd):
best_score = -float('inf')
move = -1
for spot in available_moves(brd):
brd[spot] = COMPUTER
score = minimax(brd, 0, False)
brd[spot] = spot + 1
if score > best_score:
best_score = score
move = spot
return move
def play_game():
current_player = PLAYER
while True:
print_board()
if current_player == PLAYER:
move = int(input("Make your move! (1-9): ")) - 1
if board[move] == move + 1:
board[move] = PLAYER
if check_win(board, PLAYER):
print_board()
print("Congratulations! You won!")
break
current_player = COMPUTER
else:
print("Invalid move, try again.")
else:
print("Computer's turn...")
move = top_move(board)
board[move] = COMPUTER
if check_win(board, COMPUTER):
print_board()
print("Computer wins!")
break
current_player = PLAYER
if not available_moves(board):
print_board()
print("It's a draw!")
break
play_game()
Assignment 5
Problem statement:
Implementation of Alpha-Beta Pruning for Game Tree Search.
INPUT
PLAYER_X = 'X'
PLAYER_O = 'O'
EMPTY = ' '
def alpha_beta_pruning(board, depth, alpha, beta, is_max_player):
if check_winner(board, PLAYER_X):
return 10 - depth
elif check_winner(board, PLAYER_O):
return depth - 10
elif is_board_full(board):
return 0
if is_max_player:
max_eval = float('-inf')
for row in range(3):
for col in range(3):
if board[row][col] == EMPTY:
board[row][col] = PLAYER_X
eval = alpha_beta_pruning(board, depth + 1, alpha, beta, False)
board[row][col] = EMPTY
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break
return max_eval
else:
min_eval = float('inf')
for row in range(3):
for col in range(3):
if board[row][col] == EMPTY:
board[row][col] = PLAYER_O
eval = alpha_beta_pruning(board, depth + 1, alpha, beta, True)
board[row][col] = EMPTY
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break
return min_eval
def check_winner(board, player):
for i in range(3):
if all([board[i][j] == player for j in range(3)]) or all([board[j][i] == player for j in range(3)]):
return True
if board[0][0] == player and board[1][1] == player and board[2][2] == player:
return True
if board[0][2] == player and board[1][1] == player and board[2][0] == player:
return True
return False
def is_board_full(board):
return all(all(cell != EMPTY for cell in row) for row in board)
Assignment 6
Problem statement:
Color Mapping using AI Algorithm: Constraint Specification Problem.
INPUT
def is_valid_color(graph, color, vertex, colors):
for neighbor in graph[vertex]:
if colors[neighbor] == color:
return False
return True
def graph_coloring_backtracking(graph, m, colors, vertex):
if vertex == len(graph):
return True
for color in range(1, m + 1):
if is_valid_color(graph, color, vertex, colors):
colors[vertex] = color
if graph_coloring_backtracking(graph, m, colors, vertex + 1):
return True
colors[vertex] = 0
return False
def graph_coloring(graph, m):
colors = [0] * len(graph)
if graph_coloring_backtracking(graph, m, colors, 0):
return colors
else:
return None
graph = {
0: [1, 2],
1: [0, 2],
2: [0, 1, 3],
3: [2]
}
m = 3
colors = graph_coloring(graph, m)
if colors:
print("Coloring is possible with the following color assignments:")
for i, color in enumerate(colors):
print(f"Vertex {i} -> Color {color}")
else:
print("Coloring is not possible with the given number of colors.")
Assignment 7
Problem statement:
Implement the N-Queen problem which involves placing N queens on an N×N chessboard such that no two queens threaten each other.
INPUT
def is_safe(board, row, col, N):
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, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_nqueens(board, col, N):
if col >= N:
return True
for i in range(N):
if is_safe(board, i, col, N):
board[i][col] = 1
if solve_nqueens(board, col + 1, N):
return True
board[i][col] = 0
return False
def print_solution(board, N):
for row in board:
print(" ".join(['Q' if x else '.' for x in row]))
def n_queens(N):
board = [[0 for _ in range(N)] for _ in range(N)]
if solve_nqueens(board, 0, N):
print_solution(board, N)
else:
print("No solution exists.")
N = int(input("Enter the size of the chessboard (N x N): "))
n_queens(N)
Done!
Would you also like a nicely compiled version (like all in one text file) if you want to download it directly?
Let me know!