0% found this document useful (0 votes)
11 views10 pages

All

The document contains multiple implementations of algorithms and games, including a Simple Problem Solving Agent, Depth-Limited Search, Uniform-Cost Search, Tic-Tac-Toe, the 8-Puzzle problem, and Towers of Hanoi. Each section provides source code and example usage, demonstrating how to solve specific problems or play games. The implementations showcase various programming techniques and algorithms in Python.

Uploaded by

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

All

The document contains multiple implementations of algorithms and games, including a Simple Problem Solving Agent, Depth-Limited Search, Uniform-Cost Search, Tic-Tac-Toe, the 8-Puzzle problem, and Towers of Hanoi. Each section provides source code and example usage, demonstrating how to solve specific problems or play games. The implementations showcase various programming techniques and algorithms in Python.

Uploaded by

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

Simple Problem Solving agent

class SimpleProblemSolvingAgent:
def __init__(self):
self.seq = [] # Action sequence (initially empty)
self.state = None # Current world state
self.goal = None # Goal (initially null)
self.problem = None # Problem formulation (initially null)

def update_state(self, state, percept):


"""
Update the agent's state based on percept (new information).
"""
# Example: Assume the percept is directly the state (for simplicity)
return percept

def formulate_goal(self, state):


"""
Formulate a goal based on the current state.
"""
# Example: If there is dirt, the goal is to clean it.
if "dirt" in state:
return "clean"
return None

def formulate_problem(self, state, goal):


"""
Formulate a problem given the state and goal.
"""
# Example: Problem is to move to the room with dirt and clean it.
if goal == "clean":
room = state.get("dirt_location", None)
if room:
return {"goal": "clean", "target": room}
return None

def search(self, problem):


"""
Search for a sequence of actions to solve the problem.
"""
# Example: Generate a simple action plan.
if problem and problem["goal"] == "clean":
room = problem["target"]
return [f"move to {room}", "vacuum"]
return []

def first(self, seq):


"""
Get the first action in the sequence.
"""
return seq[0] if seq else None

def rest(self, seq):


"""
Remove the first action from the sequence.
"""
return seq[1:]

def simple_problem_solving_agent(self, percept):


"""
Main function of the problem-solving agent.
"""
self.state = self.update_state(self.state, percept)

if not self.seq: # If action sequence is empty


self.goal = self.formulate_goal(self.state)
if not self.goal:
return None # No goal means no action

self.problem = self.formulate_problem(self.state, self.goal)


self.seq = self.search(self.problem)

if self.seq == []: # If no solution is found


return None

# Execute the first action in the sequence


action = self.first(self.seq)
self.seq = self.rest(self.seq)
return action

# Example usage
if __name__ == "__main__":
agent = SimpleProblemSolvingAgent()

# Simulating percepts: A room with dirt at "living room"


percepts = [
{"dirt": True, "dirt_location": "living room"},
{"dirt": False} # After cleaning
]

for percept in percepts:


action = agent.simple_problem_solving_agent(percept)
print(f"Action: {action}")

Output
Action: move to living room
Action: vacuum

def depth_limited_search(node, goal, depth_limit):


"""
Perform Depth-Limited Search on a graph.

:param node: Current node.


:param goal: Goal node to find.
:param depth_limit: Maximum depth allowed.
:return: True if goal is found, otherwise False.
"""
if node == goal:
return True
if depth_limit <= 0:
return False

# Recursively explore child nodes


for child in graph.get(node, []):
if depth_limited_search(child, goal, depth_limit - 1):
return True
return False
# Define the graph as an adjacency list
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'F': ['G', 'H']
}

# Example usage
start_node = 'A'
goal_node = 'G'
depth_limit = 2

if depth_limited_search(start_node, goal_node, depth_limit):


print(f"Goal node '{goal_node}' found within depth limit {depth_limit}.")
else:
print(f"Goal node '{goal_node}' not found within depth limit {depth_limit}.")

UCS Algorithm

import heapq

def uniform_cost_search(graph, start, goal):


"""
Perform Uniform-Cost Search to find the least-cost path.

:param graph: A dictionary where keys are nodes and values are lists of
(neighbor, cost) tuples.
:param start: The starting node.
:param goal: The goal node.
:return: A tuple containing the least-cost path and its total cost.
"""
# Priority queue to store (cost, node, path)
priority_queue = [(0, start, [])]
visited = set()

while priority_queue:
# Dequeue the node with the smallest cost
cost, node, path = heapq.heappop(priority_queue)

if node in visited:
continue

# Add the current node to the path


path = path + [node]
visited.add(node)

# Goal test
if node == goal:
return path, cost

# Expand neighbors
for neighbor, edge_cost in graph.get(node, []):
if neighbor not in visited:
heapq.heappush(priority_queue, (cost + edge_cost, neighbor, path))

return None, float('inf') # Return if no solution exists


# Example usage
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('D', 3), ('E', 1)],
'C': [('F', 1), ('G', 2)],
'E': [('G', 5)],
'F': [('G', 1)]
}

start_node = 'A'
goal_node = 'G'

path, cost = uniform_cost_search(graph, start_node, goal_node)


if path:
print(f"Least-cost path: {' -> '.join(path)}, Cost: {cost}")
else:
print("No path found.")

4.Write a Program to Implement Tic-Tac-Toe game


Source code
import random

class TicTacToe:

def __init__(self):
self.board = []

def create_board(self):
for i in range(3):
row = []
for j in range(3):
row.append('-')
self.board.append(row)

def get_random_first_player(self):
return random.randint(0, 1)

def fix_spot(self, row, col, player):


self.board[row][col] = player

def is_player_win(self, player):


win = None

n = len(self.board)

# checking rows
for i in range(n):
win = True
for j in range(n):
if self.board[i][j] != player:
win = False
break
if win:
return win

# checking columns
for i in range(n):
win = True
for j in range(n):
if self.board[j][i] != player:
win = False
break
if win:
return win
# checking diagonals
win = True
for i in range(n):
if self.board[i][i] != player:
win = False
break
if win:
return win

win = True
for i in range(n):
if self.board[i][n - 1 - i] != player:
win = False
break
if win:
return win
return False

for row in self.board:


for item in row:
if item == '-':
return False
return True

def is_board_filled(self):
for row in self.board:
for item in row:
if item == '-':
return False
return True

def swap_player_turn(self, player):


return 'X' if player == 'O' else 'O'

def show_board(self):
for row in self.board:
for item in row:
print(item, end=" ")
print()

def start(self):
self.create_board()

player = 'X' if self.get_random_first_player() == 1 else 'O'


while True:
print(f"Player {player} turn")

self.show_board()

# taking user input


row, col = list(
map(int, input("Enter row and column numbers to fix spot:
").split()))
print()

# fixing the spot


self.fix_spot(row - 1, col - 1, player)

# checking whether current player is won or not


if self.is_player_win(player):
print(f"Player {player} wins the game!")
break

# checking whether the game is draw or not


if self.is_board_filled():
print("Match Draw!")
break

# swapping the turn


player = self.swap_player_turn(player)

# showing the final view of board


print()
self.show_board()

# starting the game


tic_tac_toe = TicTacToe()
tic_tac_toe.start()

OutPut

Player O turn
- - -
- - -
- - -
Enter row and column numbers to fix spot: 1 1

Player X turn
O - -
- - -
- - -
Enter row and column numbers to fix spot: 1 2

Player O turn
O X -
- - -
- - -
Enter row and column numbers to fix spot: 2 2

Player X turn
O X -
- O -
- - -
Enter row and column numbers to fix spot: 3 3

Player O turn
O X -
- O -
- - X
Enter row and column numbers to fix spot: 1 3

Player X turn
O X O
- O -
- - X
Enter row and column numbers to fix spot: 3 1

Player O turn
O X O
- O -
X - X
Enter row and column numbers to fix spot: 3 2

Player X turn
O X O
- O -
X O X
Enter row and column numbers to fix spot: 2 3

Player O turn
O X O
- O X
X O X
Enter row and column numbers to fix spot: 2 1

Match Draw!

O X O
O O X
X O X

Write a program to implement 8 puzzle problem


SOURCE CODE
import copy
from heapq import heappush, heappop
n = 3
row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]
class priorityQueue:
def __init__(self):
self.heap = []
def push(self, k):
heappush(self.heap, k)
def pop(self):
return heappop(self.heap)
def empty(self):
if not self.heap:
return True
else:
return False
class node:
def __init__(self, parent, mat, empty_tile_pos,
cost, level):
self.parent = parent
self.mat = mat
self.empty_tile_pos = empty_tile_pos
self.cost = cost
self.level = level
def __lt__(self, nxt):
return self.cost < nxt.cost
def calculateCost(mat, final) -> int:
count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1
return count
def newNode(mat, empty_tile_pos, new_empty_tile_pos,
level, parent, final) -> node:
new_mat = copy.deepcopy(mat)
x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1]
cost = calculateCost(new_mat, final)
new_node = node(parent, new_mat, new_empty_tile_pos,
cost, level)
return new_node
def printMatrix(mat):
for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")
print()
def isSafe(x, y):
return x >= 0 and x < n and y >= 0 and y < n
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
def solve(initial, empty_tile_pos, final):
pq = priorityQueue()
cost = calculateCost(initial, final)
root = node(None, initial,
empty_tile_pos, cost, 0)
pq.push(root)
while not pq.empty():
minimum = pq.pop()
if minimum.cost == 0:
printPath(minimum)
return
for i in range(n):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]
if isSafe(new_tile_pos[0], new_tile_pos[1]):
child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)
pq.push(child)
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
empty_tile_pos = [ 1, 2 ]
solve(initial, empty_tile_pos, final)

OUTPUT:
1 2 3
5 6 0
7 8 4

1 2 3
5 0 6
7 8 4

1 2 3
5 8 6
7 0 4

1 2 3
5 8 6
7 4

6. Write a program to implement Towers of Hanoi problem


SOURCE CODE
class Tower:
def __init__(self):
self.terminate = 1
def printMove(self, source, destination):
print("{} -> {}".format(source, destination))
def move(self, disc, source, destination, auxiliary):
if disc == self.terminate:
self.printMove(source, destination)
else:
self.move(disc - 1, source, auxiliary, destination)
self.move(1, source, destination, auxiliary)
self.move(disc - 1, auxiliary, destination, source)
t = Tower();
t.move(3, 'A', 'B', 'C')

OUTPUT
A -> B
A -> C
B -> C
A -> B
C -> A
C -> B
A -> B

You might also like