0% found this document useful (0 votes)
7 views14 pages

Ai Program

The document contains implementations of various algorithms and games, including A* pathfinding, Tic-Tac-Toe, a block world planner, and a knowledge base with forward and backward chaining. Each section includes user input for defining the problem space and outputs the results of the algorithms. The programs demonstrate different approaches to problem-solving in computer science.

Uploaded by

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

Ai Program

The document contains implementations of various algorithms and games, including A* pathfinding, Tic-Tac-Toe, a block world planner, and a knowledge base with forward and backward chaining. Each section includes user input for defining the problem space and outputs the results of the algorithms. The programs demonstrate different approaches to problem-solving in computer science.

Uploaded by

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

Program

import heapq

def a_star(graph, heuristic, start, goal):

open_list = [] # Priority queue

heapq.heappush(open_list, (0 + heuristic[start], 0, start, []))

closed_list = set()

while open_list:

_, cost, current, path = heapq.heappop(open_list)

if current in closed_list:

continue

path = path + [current]

if current == goal:

return path, cost

closed_list.add(current)

for neighbor, neighbor_cost in graph[current].items():

if neighbor not in closed_list:

new_cost = cost + neighbor_cost

heapq.heappush(open_list, (new_cost + heuristic[neighbor],


new_cost, neighbor, path))

return None, float('inf')

# Taking user input

graph = {}

n = int(input("Enter the number of nodes: "))

print("Enter the adjacency list (format: node neighbor cost, type 'done' to
finish):")

for _ in range(n):

node = input("Enter node: ")


graph[node] = {}

while True:

entry = input(f"Enter neighbor and cost for {node} (or 'done'): ")

if entry.lower() == 'done':

break

neighbor, cost = entry.split()

graph[node][neighbor] = int(cost)

heuristic = {}

print("Enter heuristic values for each node:")

for node in graph.keys():

heuristic[node] = int(input(f"Heuristic value for {node}: "))

start = input("Enter start node: ")

goal = input("Enter goal node: ")

path, cost = a_star(graph, heuristic, start, goal)

if path:

print(f"Optimal path: {' -> '.join(path)} with cost {cost}")

else:

print("No path found")

Output :
Program

def print_board(board):
for row in board:

print(" | ".join(row))

print("-" * 5)

def check_winner(board):

for row in board:

if row[0] == row[1] == row[2] and row[0] != " ":

return row[0]

for col in range(3):

if board[0][col] == board[1][col] == board[2][col] and board[0][col] !


= " ":

return board[0][col]

if board[0][0] == board[1][1] == board[2][2] and board[0][0] != " ":

return board[0][0]

if board[0][2] == board[1][1] == board[2][0] and board[0][2] != " ":

return board[0][2]

return None

def is_moves_left(board):

return any(" " in row for row in board)

def tic_tac_toe():

board = [[" " for _ in range(3)] for _ in range(3)]

print("Welcome to Tic-Tac-Toe!")

print_board(board)

player = "X"

for _ in range(9):

row, col = map(int, input(f"Player {player}, enter row and column (0-
2): ").split())
if board[row][col] != " ":

print("Invalid move! Try again.")

continue

board[row][col] = player

print_board(board)

if check_winner(board):

print(f"Player {player} wins!")

return

player = "O" if player == "X" else "X"

print("It's a draw!")

tic_tac_toe()

Output
Program
def print_state(state):

"""Prints the current state of stacks."""

for stack in state:

print(stack)

print("---")

def move_block(state, from_stack, to_stack):

"""Moves the top block from one stack to another."""

if state[from_stack]: # Ensure there is a block to move

block = state[from_stack].pop()

state[to_stack].append(block)

return True

return False

def is_goal_reached(state, goal):

"""Checks if the current state matches the goal state."""

return state == goal

def find_best_move(state, goal):

"""

Finds the best move by identifying which block is misplaced

and where it should go according to the goal state.

"""

for i in range(len(state)):

if state[i]: # If the stack is not empty

block = state[i][-1] # Topmost block of stack i

# Find the correct stack for this block in the goal state

for j in range(len(state)):
if block in goal[j]: # If the block belongs to stack j in goal

correct_position = goal[j].index(block)

# Check if it's the right time to move it

if len(state[j]) <= correct_position:

return i, j # Move block from i to j

return None, None # No valid move found

def block_world_planner(initial, goal):

"""

Implements a planning-based approach to reach the goal state.

"""

state = [list(stack) for stack in initial] # Copy initial state

print("Initial State:")

print_state(state)

move_count = 0 # Track the number of moves

while not is_goal_reached(state, goal):

from_stack, to_stack = find_best_move(state, goal)

if from_stack is None or to_stack is None:

print("No valid moves available. The system is stuck!")

break

move_block(state, from_stack, to_stack)

move_count += 1
print(f"Step {move_count}: Moved block from Stack {from_stack} to
Stack {to_stack}")

print_state(state)

if is_goal_reached(state, goal):

print("Goal State Reached!")

print_state(state)

# Taking user input

num_stacks = int(input("Enter the number of stacks: "))

initial = []

goal = []

print("Enter the initial state (blocks in each stack separated by space,


empty stack as -):")

for _ in range(num_stacks):

stack = input().split()

initial.append([] if stack == ['-'] else stack)

print("Enter the goal state (same format as above):")

for _ in range(num_stacks):

stack = input().split()

goal.append([] if stack == ['-'] else stack)

block_world_planner(initial, goal)

Output
Program :

class KnowledgeBase:

def __init__(self):

self.facts = set() # Set to store known facts

self.rules = [] # List of tuples (conditions, conclusion)

def add_fact(self, fact):

"""Add a known fact to the knowledge base."""

self.facts.add(fact)

def add_rule(self, conditions, conclusion):

"""Add a rule to the knowledge base."""

self.rules.append((set(conditions), conclusion))

def forward_chaining(self, goal):

"""Perform forward chaining to infer new facts."""

inferred = True

while inferred:

inferred = False

for conditions, conclusion in self.rules:

if conditions.issubset(self.facts) and conclusion not in self.facts:

self.facts.add(conclusion)

print(f"Inferred: {conclusion}")

inferred = True

if conclusion == goal:

return True

return goal in self.facts

def backward_chaining(self, goal, visited=None):


"""Perform backward chaining to check if a goal can be derived."""

if visited is None:

visited = set()

if goal in visited:

return False # Prevent infinite loops

visited.add(goal)

# Directly known fact

if goal in self.facts:

print(f"✓ {goal} is already known.")

return True

# Check rules that conclude the goal

for conditions, conclusion in self.rules:

if conclusion == goal:

print(f"Checking if {goal} can be inferred from {conditions}...")

if all(self.backward_chaining(cond, visited) for cond in


conditions):

print(f"✓ {goal} is proven by {conditions}.")

return True

else:

print(f"✘ {goal} cannot be proven from {conditions}.")

return False

# User input

kb = KnowledgeBase()

num_facts = int(input("Enter number of facts: "))

print("Enter the known facts:")


for _ in range(num_facts):

kb.add_fact(input().strip())

num_rules = int(input("Enter number of rules (IF conditions THEN


conclusion): "))

print("Enter the rules in format 'A B -> C':")

for _ in range(num_rules):

rule_input = input().strip().split("->")

conditions = rule_input[0].strip().split()

conclusion = rule_input[1].strip()

kb.add_rule(conditions, conclusion)

goal = input("Enter the goal to check: ")

# Applying Forward Chaining

print("\nApplying Forward Chaining...")

if kb.forward_chaining(goal):

print(f"🔄 Goal '{goal}' is proven by Forward Chaining!")

else:

print(f"❌ Goal '{goal}' cannot be proven by Forward Chaining.")

# Reset knowledge base for Backward Chaining

kb_backward = KnowledgeBase()

for fact in ['Rain', 'Cloudy']:

kb_backward.add_fact(fact)

for conditions, conclusion in kb.rules:

kb_backward.add_rule(conditions, conclusion)
# Applying Backward Chaining

print("\nApplying Backward Chaining...")

if kb_backward.backward_chaining(goal):

print(f"🔄 Goal '{goal}' is proven by Backward Chaining!")

else:

print(f"❌ Goal '{goal}' cannot be proven by Backward Chaining.")

Output :

You might also like