0% found this document useful (0 votes)
9 views20 pages

Ai Rec

The document contains a collection of programming problems and their solutions, including algorithms for games like Tic-Tac-Toe, tree traversal methods (inorder, preorder, postorder), and search algorithms (breadth-first and depth-first). It also includes implementations for solving Sudoku and a backward chaining inference system. Each section provides source code and sample outputs for clarity.

Uploaded by

akdk20036
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)
9 views20 pages

Ai Rec

The document contains a collection of programming problems and their solutions, including algorithms for games like Tic-Tac-Toe, tree traversal methods (inorder, preorder, postorder), and search algorithms (breadth-first and depth-first). It also includes implementations for solving Sudoku and a backward chaining inference system. Each section provides source code and sample outputs for clarity.

Uploaded by

akdk20036
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/ 20

INDEX

S.NO DATE TITLE PAGE NO. STAFF SIGN

1. WATER JUG PROBLEM

2. TIC-TAC-TOE

3. BREADTH FIRST SEARCH

4. DEPTH FIRST SEARCH

5. INORDER TRAVERSALS

6. PREORDER TRAVERSALS

7. POSTORDER TRAVERSALS

8. SUDOKU

9. BACKWARD CHAINING

10. FORWARD CHAINING

11. CALENDAR
SOURCE CODE:

x=int(input("Enter x : "))
y=int(input("Enter y :
"))while True:
rno=int(input("Enter Rule No
: "))#Fill Jar1
if rno==1:
if x<4:
x=4 #Fill
Jar2
if rno==2:
if y<3:
y=3
#Empty
Jar1 if
rno==5:
if x>0:
x=0
#Empty
Jar2 if
rno==6:
if y<0: y=0
#Pour water from Jar2 to Fill
Jar1if rno==7:
if x+y >= 4 and y > 0: x,y=4,y-
(4-x)#Pour water from Jar1 to Fill
Jar2
if rno==8:
if x+y >= 3 and y > 0: x,y=x-(3-
y),3#Pour water from Jar2 to Jar1
if rno==9:
if x+y <= 4 and y > 0:
x,y=x+y,0 #Pour water from
Jar1 to Fill Jar2if rno==10:
if x+y <= 3 and y > 0:
x,y=2,(x+y)print("x = ",x)
print("y =
",y)if(x
== 2):
print("This is the Goal
State")break
OUTPUT:

Enter x : 0
Enter y : 0
Enter Rule No : 2
x=0
y= 3
Enter Rule No : 9
x = 3y = 0
Enter Rule No : 2
x=3
y= 3
Enter Rule No : 7
x=4
y= 2
Enter Rule No : 5
x=0
y= 2
Enter Rule No : 9
x=2
y= 0
This is the Goal State

RESULT:
SOURCE CODE:

#TIC TAC TOE


theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
'4': ' ' , '5': ' ' , '6': ' ' ,
'1': ' ' , '2': ' ' , '3': ' ' }
def printBoard(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])

def game():
turn = 'X'
count = 0

for i in range(10):
printBoard(theBoard)
print("It's your turn," + turn + ".Move to which place?")
move = input()
if theBoard[move] == ' ':
theBoard[move] = turn
count += 1
else:
print("That place is already filled.\nMove to which place?")
continue

if count >= 5:
if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ':
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ':
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ':
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ':
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ':
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ':
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ':
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ':
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
if count == 9:
print("\nGame Over.\n")
print("It's a Tie!!")
# Now we have to change the player after every move.
if turn =='X':
turn = 'O'
else:
turn = 'X'
# Now we will ask if player wants to restart the game or not.
restart = input("Do want to play Again?(y/n)")
if restart == "y" or restart == "Y":
for key in theBoard.keys():
theBoard[key] = " "
game()

if name == " main ":


game()
OUTPUT:
||
-+-+-
||
-+-+-
||
It's your turn,X.Move to which place?1
||
-+-+-
||
-+-+-
X| |
It's your turn,O.Move to which place?4
||
-+-+-
O| |
-+-+-
X| |
It's your turn,X.Move to which place?9
| |X
-+-+-
O| |
-+-+-
X| |
It's your turn,O.Move to which place?5
| |X
-+-+-
O|O|
-+-+-
X| |
It's your turn,X.Move to which place?3
| |X
-+-+-
O|O|
-+-+-
X| |X
It's your turn,O.Move to which place?6
| |X
-+-+-
O|O|O
-+-+-
X| |X
Game Over.
**** O won. ****
Do want to play Again?(y/n)n

RESULT:
SOURCE CODE:

#Breadth first search


graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue

defbfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
OUTPUT:

A
B
D
E
F
C

RESULT:
SOURCE CODE:

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
dfs(visited, graph, 'A')

OUTPUT:

A
B
D
E
F
C

RESULT:
SOURCE CODE:

#INOrder TRAVERSALS
# Python program to for tree traversals

# A class that represents an individual node in a


# Binary Tree
class Node:
def init (self, key):
self.left = None
self.right = None
self.val = key

# A function to do inorder tree traversal


def printInorder(root):

if root:

# First recur on left child


printInorder(root.left)

# then print the data of node


print(root.val),

# now recur on right child


printInorder(root.right)

# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print ("\nInorder traversal of binary tree is")


printInorder(root)
OUTPUT:

Inorder traversal of binary tree is


4
2
5
1
3

RESULT:
SOURCE CODE:

#PreOrder Traversal
class Node:
def init (self, key):
self.left = None
self.right = None
self.val = key

# A function to do preorder tree traversal


def printPreorder(root):

if root:
print(root.val)
printPreorder(root.left),
printPreorder(root.right)
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print ("\nPreorder traversal of binary tree is")


printPreorder(root)

OUTPUT:

Preorder traversal of binary tree is


1
2
4
5
3

RESULT:
SOURCE CODE:

class Node:
def init (self, key):
self.left = None
self.right = None
self.val = key

# A function to do preorder tree traversal


def printPostorder(root):

if root:
printPostorder(root.left),
printPostorder(root.right)
print(root.val)
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print ("\nPostorder traversal of binary tree is")


printPostorder(root)

OUTPUT:

Postorder traversal of binary tree is


4
5
2
3
1

RESULT:
SOURCE CODE:

#SUDOKU
size = 9
#empty cells have value zero
matrix = [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]

#print sudoku
def print_sudoku():
for i in matrix:
print (i)

#assign cells and check


def number_unassigned(row, col):
num_unassign = 0
for i in range(0,size):
for j in range (0,size):
#cell is unassigned
if matrix[i][j] == 0:
row = i
col = j
num_unassign = 1
a = [row, col, num_unassign]
return a
a = [-1, -1, num_unassign]
return a
#check validity of number
def is_safe(n, r, c):
#checking in row
for i in range(0,size):
#there is a cell with same value
if matrix[r][i] == n:
return False
#checking in column
for i in range(0,size):
#there is a cell with same value
if matrix[i][c] == n:
return False
row_start = (r//3)*3
col_start = (c//3)*3;
#checking submatrix
for i in range(row_start,row_start+3):
for j in range(col_start,col_start+3):
if matrix[i][j]==n:
return False
return True
#check validity of number
def solve_sudoku():
row = 0
col = 0
#if all cells are assigned then the sudoku is already solved
#pass by reference because number_unassigned will change the values of row and col
a = number_unassigned(row, col)
if a[2] == 0:
return True
row = a[0]
col = a[1]
#number between 1 to 9
for i in range(1,10):
#if we can assign i to the cell or not
#the cell is matrix[row][col]
if is_safe(i, row, col):
matrix[row][col] = i
#backtracking
if solve_sudoku():
return True
#f we can't proceed with this solution
#reassign the cell
matrix[row][col]=0
return False

if solve_sudoku():
print_sudoku()
else:
print("No solution")
OUTPUT:

[5, 3, 4, 6, 7, 8, 9, 1, 2]
[6, 7, 2, 1, 9, 5, 3, 4, 8]
[1, 9, 8, 3, 4, 2, 5, 6, 7]
[8, 5, 9, 7, 6, 1, 4, 2, 3]
[4, 2, 6, 8, 5, 3, 7, 9, 1]
[7, 1, 3, 9, 2, 4, 8, 5, 6]
[9, 6, 1, 5, 3, 7, 2, 8, 4]
[2, 8, 7, 4, 1, 9, 6, 3, 5]
[3, 4, 5, 2, 8, 6, 1, 7, 9]

RESULT:
SOURCE CODE:

#BACKWARD CHAINING
global facts
global is_changed
is_changed = True
facts = [["vertebrate","duck"],["flying","duck"],["mammal","cat"]]

def assert_fact(fact):
global facts
global is_changed
if not fact in facts:
facts += [fact]
is_changed = True

while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "mammal":
assert_fact(["vertebrate",A1[1]])
if A1[0] == "vertebrate":
assert_fact(["animal",A1[1]])
if A1[0] == "vertebrate" and ["flying",A1[1]] in facts:
assert_fact(["bird",A1[1]])

print(facts)

OUTPUT:

[['vertebrate', 'duck'], ['flying', 'duck'], ['mammal', 'cat'], ['animal', 'duck'], ['bird', 'duck'], ['vertebrate', 'cat'],
['animal', 'cat']]

RESULT:
SOURCE CODE:

#Forward Chaining
global facts
global is_changed
is_changed = True
facts = [["plant","mango"],["eating","mango"],["seed","sprouts"]]

def assert_fact(fact):
global facts
global is_changed
if not fact in facts:
facts += [fact]
is_changed = True

while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "seed":
assert_fact(["plant",A1[1]])
if A1[0] == "plant":
assert_fact(["fruit",A1[1]])
if A1[0] == "plant" and ["eating",A1[1]] in facts:
assert_fact(["human",A1[1]])

print(facts)

OUTPUT:

['plant', 'mango'], ['eating', 'mango'], ['seed', 'sprouts'], ['fruit', 'mango'], ['human', 'mango'],
['plant', 'sprouts'], ['fruits', 'sprouts']]

RESULT:
SOURCE CODE:

#Calendar
# import module

import calendar
yy = 0
mm = 0

# To ask month and year from the user


yy = int(input("Enter year: "))
mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy, mm))
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy, mm))
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy, mm))
OUTPUT:

Enter year: 2022


Enter month: 4

April 2022
Mo Tu We Th Fr Sa Su
123
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

Enter year: 2022


Enter month: 5

May 2022
Mo Tu We Th Fr Sa Su
1
234 56 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

Enter year: 2022


Enter month: 6

June 2022
Mo Tu We Th Fr Sa Su
12345
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

RESULT:

You might also like