0% found this document useful (0 votes)
16 views13 pages

AI Experiment Part 2

python experiment

Uploaded by

Khushi Kumari
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)
16 views13 pages

AI Experiment Part 2

python experiment

Uploaded by

Khushi Kumari
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/ 13

Tic-Tac-Toe

def ConstBoard(board):
print("Current State Of Board : \n\n")
for i in range(0, 9):
if (i > 0) and (i % 3) == 0:
print("\n")
if board[i] == 0:
print("- ", end=" ")
if board[i] == 1:
print("O ", end=" ")
if board[i] == -1:
print("X ", end=" ")
print("\n\n")

def User1Turn(board):
pos = input("Enter X's position from [1...9]: ")
pos = int(pos)
if board[pos - 1] != 0:
print("Wrong Move!!!")
exit(0)
board[pos - 1] = -1

def User2Turn(board):
pos = input("Enter O's position from [1...9]: ")
pos = int(pos)
if board[pos - 1] != 0:
print("Wrong Move!!!")
exit(0)
board[pos - 1] = 1

# MinMax function.
def minimax(board, player):
x = analyzeboard(board)
if x != 0:
return x * player
pos = -1
value = -2
for i in range(0, 9):
if board[i] == 0:
board[i] = player
score = -minimax(board, (player * -1))
if score > value:
value = score
pos = i
board[i] = 0

if pos == -1:
return 0
return value

def CompTurn(board):
pos = -1
value = -2
for i in range(0, 9):
if board[i] == 0:
board[i] = 1
score = -minimax(board, -1)
board[i] = 0
if score > value:
value = score
pos = i

board[pos] = 1

def analyzeboard(board):
cb = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]]

for i in range(0, 8):


if (board[cb[i][0]] != 0 and
board[cb[i][0]] == board[cb[i][1]] and
board[cb[i][0]] == board[cb[i][2]]):
return board[cb[i][2]]
return 0

def main():
choice = input("Enter 1 for single player, 2 for multiplayer: ")
choice = int(choice)

board = [0, 0, 0, 0, 0, 0, 0, 0, 0]
if choice == 1:
print("Computer : O Vs. You : X")
player = input("Enter to play 1(st) or 2(nd) :")
player = int(player)
for i in range(0, 9):
if analyzeboard(board) != 0:
break
if (i + player) % 2 == 0:
CompTurn(board)
else:
ConstBoard(board)
User1Turn(board)
else:
for i in range(0, 9):
if analyzeboard(board) != 0:
break
if i % 2 == 0:
ConstBoard(board)
User1Turn(board)
else:
ConstBoard(board)
User2Turn(board)

x = analyzeboard(board)
if x == 0:
ConstBoard(board)
print("Draw!!!")
if x == -1:
ConstBoard(board)
print("X Wins!!! Y Loose !!!")
if x == 1:
ConstBoard(board)
print("X Loose!!! O Wins !!!!")

main()
Output:
Enter 1 for single player, 2 for multiplayer: 1
Computer : O Vs. You : X
Enter to play 1(st) or 2(nd) :1
Current State Of Board :

- - -

- - -

- - -

Enter X's position from [1...9]: 1


Current State Of Board :

X - -

- O -

- - -

Enter X's position from [1...9]: 3


Current State Of Board :

X O X

- O -

- - -

Enter X's position from [1...9]: 8


Current State Of Board :

X O X

O O -

- X -

Enter X's position from [1...9]: 6


Current State Of Board :

X O X

O O X

- X O

Enter X's position from [1...9]: 7


Current State Of Board :
X O X

O O X

X X O

Draw!!!

Process finished with exit code 0


n-Queen’s
def solve_n_queens(n):
def is_safe(board, row, col):
for i in range(row):
if board[i][col] == 'Q':
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 'Q':
return False
for i, j in zip(range(row, -1, -1), range(col, n)):
if board[i][j] == 'Q':
return False
return True

def backtrack(board, row):


if row == n:
return board
for col in range(n):
if is_safe(board, row, col):
board[row][col] = 'Q'
result = backtrack(board, row + 1)
if result is not None:
return result
board[row][col] = '0'
return None

board = [['0' for _ in range(n)] for _ in range(n)]


result = backtrack(board, 0)
if result is None:
print("No solution exists for n = {}".format(n))
else:
for row in result:
print(' '.join(row).replace('0', '.').replace('Q', 'Q '))

n = int(input("Enter the value of n: "))


solve_n_queens(n)
Output:
Enter the value of n: 27
Q . . . . . . . . . . . . . . . . . . . . . . . . . .
. . Q . . . . . . . . . . . . . . . . . . . . . . . .
. . . . Q . . . . . . . . . . . . . . . . . . . . . .
. Q . . . . . . . . . . . . . . . . . . . . . . . . .
. . . Q . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . Q . . . . . . . . . . . . . . . . . .
. . . . . . . . . . Q . . . . . . . . . . . . . . . .
. . . . . . . . . . . . Q . . . . . . . . . . . . . .
. . . . . . . . . . . . . . Q . . . . . . . . . . . .
. . . . . . . . . . . . . . . . Q . . . . . . . . . .
. . . . . . . . . . . . . . . . . . Q . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . Q . . . .
. . . . . . . . . . . . . . . . . . . . . . . . Q . .
. . . . . . . . . . . . . . . . . . . . . . . . . . Q
. . . . . . . . . . . . . . . . . . . . . . . Q . . .
. . . . . . . . . . . . . . . . . . . . . . . . . Q .
. . . . . Q . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . Q . . . . . . . . . . . . . . . . .
. . . . . . Q . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . Q . . . . . . . . . . .
. . . . . . . Q . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . Q . . . . . . . . . . . . . . .
. . . . . . . . . . . . . Q . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . Q . . . . . .
. . . . . . . . . . . . . . . . . Q . . . . . . . . .
. . . . . . . . . . . . . . . . . . . Q . . . . . . .
. . . . . . . . . . . . . . . . . . . . . Q . . . . .

Process finished with exit code 0

Blocks’ world hill climbing


import random

class BlocksWorld:
def __init__(self, initial_state, goal_state):
self.initial_state = initial_state
self.goal_state = goal_state

def generate_random_action(self):
actions = ['Move A onto B', 'Move A over B', 'Move B onto A', 'Move
B over A']
return random.choice(actions)

def apply_action(self, state, action): # Added missing colon


idx_A = None
idx_B = None
new_state = [stack[:] for stack in state] # Create a new state to
avoid modifying the original state
if 'onto' in action:
block_A, block_B = action.split(' onto ')
for i in range(len(new_state)):
if block_A in new_state[i]:
idx_A = i
if block_B in new_state[i]:
idx_B = i
if idx_A is not None and idx_B is not None:
new_state[idx_A] = [block for block in new_state[idx_A] if
block != block_A]
new_state[idx_B].append(block_A)
elif 'over' in action:
block_A, block_B = action.split(' over ')
for i in range(len(new_state)):
if block_A in new_state[i]:
idx_A = i
if block_B in new_state[i]:
idx_B = i
if idx_A is not None and idx_B is not None:
new_state[idx_A] = [block for block in new_state[idx_A] if
block != block_A]
new_state[idx_B].append(block_A)
return new_state

def is_goal_state(self, state):


return state == self.goal_state

def hill_climbing(self, max_iterations=1000):


current_state = self.initial_state
iteration = 0
print("Initial state:")
self.print_state(current_state)
while not self.is_goal_state(current_state) and iteration <
max_iterations:
action = self.generate_random_action()
next_state = self.apply_action(current_state, action)
iteration += 1
print(f"\nState after move {iteration}:")
self.print_state(next_state)
if self.is_better_state(next_state, current_state):
current_state = next_state
else:
print("No better move found at move", iteration,
"continuing...")
if self.is_goal_state(current_state):
print("\nGoal state achieved:")
self.print_state(current_state)
else:
print("\nFailed to reach the goal state within the maximum
number of iterations.")
return current_state

def is_better_state(self, next_state, current_state):


return self.evaluate_state(next_state) >
self.evaluate_state(current_state)

def evaluate_state(self, state):


correct_blocks = 0
min_len = min(len(state), len(self.goal_state))
for i in range(min_len):
if state[i] == self.goal_state[i]:
correct_blocks += 1
return correct_blocks

def print_state(self, state):


for i in range(len(state)):
print(f"Stack {i + 1}: {', '.join(state[i]) if state[i] else
''}")

def get_initial_state():
print("Enter the initial state (press Enter after each stack, leave
empty and press Enter to finish):")
initial_state = []
while True:
stack = input("Enter blocks for stack: ").split()
if not stack:
break
initial_state.append(stack)
return initial_state

def get_goal_state():
print("\nEnter the goal state (press Enter after each stack, leave
empty and press Enter to finish):")
goal_state = []
while True:
stack = input("Enter blocks for stack: ").split()
if not stack:
break
goal_state.append(stack)
return goal_state

initial_state = get_initial_state()
goal_state = get_goal_state()

blocks_world = BlocksWorld(initial_state, goal_state)


final_state = blocks_world.hill_climbing(max_iterations=100)

if final_state:
print("\nGoal state achieved:")
blocks_world.print_state(final_state)
else:
print("\nFailed to reach the goal state within the maximum number of
iterations.")
output
Enter the initial state (press Enter after each stack, leave empty and
press Enter to finish):
Enter blocks for stack: A B
Enter blocks for stack: C D
Enter blocks for stack:
Enter blocks for stack:

Enter the goal state (press Enter after each stack, leave empty and press
Enter to finish):
Enter blocks for stack: C D
Enter blocks for stack: A B
Enter blocks for stack:

Initial state:
Stack 1: A, B
Stack 2: C, D

State after move 1:


Stack 1: A
Stack 2: C, D, B

State after move 2:


Stack 1: A, D
Stack 2: C, B

State after move 3:


Stack 1: A, D
Stack 2: C, B

State after move 4:


Stack 1: A, D, C
Stack 2: B

Goal state achieved:


Stack 1: A, D, C
Stack 2: B
Cryptarithmetic puzzle
import itertools

def solve_cryptarithmetic(puzzle):
puzzle = puzzle.replace(' ', '')
puzzle = puzzle.replace('=', '==')
letters = set(char for char in puzzle if char.isalpha())
digits = '1234567890'
for perm in itertools.permutations(digits, len(letters)):
mapping = dict(zip(letters, perm))
if evaluate(puzzle, mapping):
print(mapping)
return
print("No solution found.")

def evaluate(puzzle, mapping):


equation = ''.join(mapping.get(char, char) for char in puzzle)

if any(part.lstrip('0') != part for part in equation.split('+')):


return False
try:
return eval(equation)
except ArithmeticError:
return False

puzzle = input("Enter the cryptarithmetic puzzle (use '+' for addition and '=' for equality): ")
solve_cryptarithmetic(puzzle)

OUTPUT:
1.
Enter the cryptarithmetic puzzle (use '+' for addition and '=' for equality): SEND + MORE = MONEY
{'O': '0',
'S': '9',
'N': '6',
'E': '5',
'M': '1',
'D': '7',
'R': '8',
'Y': '2'}

Process finished with exit code 0


Prolog Program:
%facts
male(ram).
male(rohan).
male(sai).
female(sharon).
female(sonam).
female(nisa).

father(sai,ram).
father(ram,nisa).
father(ram,rohan).
mother(sharon,nisa).
mother(sharon,rohan).

%rule
sibling(X,Y):-father(Z,X),father(Z,Y),mother(W,X),mother(W,Y).
sister(X,Y):-female(X),sibling(X,Y).
grandfather(X,Y):-father(X,A),father(A,Y).
Output:
Warning: make_directory/1: directory `'//Mac/Home/Documents/Prolog'' does
not exist (No such file or directory)
Welcome to SWI-Prolog (threaded, 64 bits, version 9.0.4)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.
For online help and background, visit https://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- consult('C:\\prolog\\AI_Expt_8.pl').
true.

?- male(ram).
true.

?- male(nisa).
false.

?- male(X).
X = ram ;
X = rohan ;
X = sai.

?- female(X).
X = sharon ;
X = sonam ;
X = nisa.

?- father(X,Y).
X = sai,
Y = ram ;
X = ram,
Y = nisa ;
X = ram,
Y = rohan.

?- mother(X,Y).
X = sharon,
Y = nisa ;
X = sharon,
Y = rohan.

?- sibling(X,Y).
X = Y, Y = nisa ;
X = nisa,
Y = rohan ;
X = rohan,
Y = nisa ;
X = Y, Y = rohan.

?- grandfather(X,Y).
X = sai,
Y = nisa ;
X = sai,
Y = rohan ;
false.

?- sibling(sonam,rohan).
false.

You might also like