0% found this document useful (0 votes)
4 views30 pages

AI Lab Experiments

The document outlines the academic framework and objectives of the Artificial Intelligence Lab at Siddharth Institute of Engineering & Technology. It includes the institute's vision and mission, program outcomes, educational objectives, specific outcomes, safety guidelines for the lab, course objectives, and a list of programming experiments in Python. The document serves as a comprehensive guide for students in the Computer Science and Engineering department to understand the course structure and expectations.
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)
4 views30 pages

AI Lab Experiments

The document outlines the academic framework and objectives of the Artificial Intelligence Lab at Siddharth Institute of Engineering & Technology. It includes the institute's vision and mission, program outcomes, educational objectives, specific outcomes, safety guidelines for the lab, course objectives, and a list of programming experiments in Python. The document serves as a comprehensive guide for students in the Computer Science and Engineering department to understand the course structure and expectations.
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

SIDDHARTH INSTITUTE OF ENGINEERING & TECHNOLOGY

(AUTONOMOUS)
(Approved by AICTE, New Delhi& Affiliated to JNTUA, Ananthapuramu)
(Accredited by NBA for Civil, EEE, Mech., ECE & CSE
Accredited by NAAC with ‘A+’ Grade)
Puttur -517583, Tirupati District, A.P. (India)

Department of Computer Science and Engineering


(Common to CSM and CAD)
(20CS0902) ARTIFICIAL INTELLIGENCE LAB
II [Link] -II Semester

Lab Observation Book


Academic Year: _____________________________________________

Name : ____________________________________________

Roll. Number : ____________________________________________

Year & Branch: _____________________________________________

Specialization : _____________________________________________
SIDDHARTH INSTITUTE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
(Approved by AICTE, New Delhi& Affiliated to JNTUA, Ananthapuramu)
(Accredited by NBA for Civil, EEE, Mech., ECE & CSE
Accredited by NAAC with ‘A’ Grade)
Puttur -517583, Tirupati District, A.P. (India)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

INSTITUTE VISION
To emerge as one of the premier institutions through excellence in education and research,
producing globally competent and ethically strong professionals and entrepreneurs

INSTITUTE MISSION
M1: Imparting high-quality technical and management education through the state-of-
the- art resources.
M2: Creating an eco-system to conduct independent and collaborative research for the
betterment of the society
M3: Promoting entrepreneurial skills and inculcating ethics for the socio-economic
development of the nation.

DEPARTMENT VISION
To impart quality education and research in Computer Science and Engineering for producing
technically competent and ethically strong IT professionals with contemporary knowledge

DEPARTMENT MISSION
M1: Achieving academic excellence in computer science through effective pedagogy,
modern curriculum and state-of-art computing facilities.
M2: Encouraging innovative research in Computer Science and Engineering by
collaborating with Industry and Premier Institutions to serve the nation.
M3: Empowering the students by inculcating professional behavior, strong ethical
values and leadership abilities
SIDDHARTH INSTITUTE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
(Approved by AICTE, New Delhi& Affiliated to JNTUA, Ananthapuramu)
(Accredited by NBA for Civil, EEE, Mech., ECE & CSE
Accredited by NAAC with ‘A’ Grade)
Puttur -517583, Tirupati District, A.P. (India)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Program Outcomes
PO1: Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.

PO2: Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.

PO3: Design/Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, and the cultural, societal, and environmental considerations.

PO4: Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO5: Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.

PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

PO7: Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9: Individual and Team Work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.

PO11: Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.

PO12: Life-Long Learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
SIDDHARTH INSTITUTE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
(Approved by AICTE, New Delhi& Affiliated to JNTUA, Ananthapuramu)
(Accredited by NBA for Civil, EEE, Mech., ECE & CSE
Accredited by NAAC with ‘A’ Grade)
Puttur -517583, Tirupati District, A.P. (India)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


PEO1: To provide software solutions for arising problems in diverse areas with strong
knowledge in innovative technologies of computer science.
PEO2: To serve in IT industry as professionals and entrepreneurs or in pursuit of higher
education and research.
PEO3: To attain professional etiquette, soft skills, leadership, ethical values meld with a
commitment for lifelong learning.

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO1: Analysis & Design: Ability to design, develop and deploy customized
applications in all applicable domains using various algorithms and programming
languages.
PSO2: Computational Logic: Ability to visualize and configure computational need in
terms of hardware and software to provide solutions for various complex
applications.
PSO3: Software Development: Ability to apply standard procedures, tools and strategies
for software development.
Do’s:

1. Know the location of the fire extinguisher and the first aid box and how to use them in case
of an emergency.

2. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.

3. Report fires or accidents to your lecturer/laboratory technician immediately.

4. Report any broken plugs or exposed electrical wires to your lecturer/laboratory technician
immediately.

Don’ts:

1. Do not eat or drink in the laboratory.

2. Avoid stepping on electrical wires or any other computer cables.

3. Do not open the system unit casing or monitor casing particularly when the power is turned
on. Some internal components hold electric voltages of up to 30000 volts, which can be fatal.

4. Do not insert metal objects such as clips, pins and needles into the computer casings. They
may cause fire.

5. Do not remove anything from the computer laboratory without permission.

6. Do not touch, connect or disconnect any plug or cable without your lecturer/laboratory
technician’s permission.

7. Do not misbehave in the computer laboratory.


COURSE OBJECTIVES
The objective of the course is to

1. To provide a basic foundation on python Tool.


2. To Build various applications of AI such as Back propagation algorithm, Hangman
game.
3. Explore the scope, advantages as well as limitations of intelligent systems.
4. Experiment with different machine learning concepts such as Deep Learning and
Reinforcement Learning
5. To expose students to the AI-intensive computing and information system frameworks.

COURSE OUTCOMES
On successful completion of the course, the students will be able to
1. Identify various domains in which AI can be applied
2. Analyze the standard logics and algorithm of AI
3. Implementing the examples of AI
4. Implementing the Searching techniques
5. Implementing the Knowledge representation Systems
6. Understand the python programming in various domains

List of Experiments:

1. A) Write a Program to implement Breadth First Search in Python.


B) Write a Program to implement Depth First Search in Python.
2. A) Write a Program to implement Water-Jug problem in Python.
B) Write a Program to implement N-Queens Problem in Python
3. A) Write a Program to implement Tower of Hanoi in Python.
B) Write a Program to implement Travelling Salesman Problem in Python.
4. Write a Program to implement Greedy Best First Search in Python.
5. Write a Program to implement A*Search Algorithm in Python.
6. Write a Program to implement IDA*Search Algorithm in Python.
7. Write a Program to implement Alpha-Beta Pruning in Python.
8. Write a Program to implement Tic-Tac-Toe game in Python.
9. Write a Program to implement Natural Deduction System in Python.
10. Write a Program to implement Axiomatic System in Python.
11. Write a Program to implement KR using Semantic Network in Python.
12. Write a Program to implement Conceptual Dependency Theory in Python.
1. A) Write a Program to implement Breadth First Search using Python.

Aim:

To write a python program for implementing Breadth First Search.

Program:

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue

def bfs(visited, graph, node):


[Link](node)
[Link](node)

while queue:
s = [Link](0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
[Link](neighbour)
[Link](neighbour)

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

Output:

ABCDEF

Result:

Hence, the implementation of Breadth First Search using python is written and
executed successfully.
1. B) Write a Program to implement Depth First Search using Python.

Aim:

To write a python program for implementing Depth First Search.

Program:

# Using a Python dictionary to act as an adjacency list


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)
[Link](node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

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

Output:

A
B
D
E
F
C

Result:

Hence, the implementation of Depth First Search using python is written and executed
successfully.
2. A) Write a Program to implement Water-Jug problem using Python.

Aim:

To write a python program for implementing Water-Jug problem.

Program:
# This function is used to initialize the
# dictionary elements with a default value.
from collections import defaultdict

# jug1 and jug2 contain the value


jug1, jug2, aim = 4, 3, 2

# Initialize dictionary with


# default value as false.
visited = defaultdict(lambda: False)
def waterJugSolver(amt1, amt2):
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True
if visited[(amt1, amt2)] == False:
print(amt1, amt2)
visited[(amt1, amt2)] = True
return (waterJugSolver(0, amt2) or waterJugSolver(amt1, 0) or
waterJugSolver(jug1, amt2) or waterJugSolver(amt1, jug2) or waterJugSolver(amt1 +
min(amt2, (jug1-amt1)), amt2 - min(amt2, (jug1-amt1))) or waterJugSolver(amt1 -
min(amt1, (jug2-amt2)), amt2 + min(amt1, (jug2-amt2))))
else:
return False
print("Steps: ")
waterJugSolver(0, 0)

Output:
Steps:
00
40
43
03
30
33
42
02
True

Result:

Hence, the implementation of Water Jug Problem using python is written and
executed successfully.
2. B) Write a Program to implement N-Queens Problem using Python

Aim:

To write a python program for implementing N-Queen Problem.

Program:

# Taking number of queens as input from user

print ("Enter the number of queens")


N = int(input())

# here we create a chessboard


# NxN matrix with all elements set to 0

board = [[0]*N for _ in range(N)]


def attack(i, j):
#checking vertically and horizontally
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True

#checking diagonally
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False

def N_queens(n):
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)
Output:

Enter the number of queens


8

[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]

Result:

Hence, the implementation of N-Queen Problem using python is written and executed
successfully.
3. A) Write a Program to implement Tower of Hanoi using Python.

Aim:

To write a python program for implementing Tower of Hanoi concept.

Program:
def tower_of_hanoi(n, from_rod, to_rod, aux_rod):
if n == 1:
print("Move disk 1 from", from_rod, "to", to_rod)
return
tower_of_hanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk", n, "from", from_rod, "to", to_rod)
tower_of_hanoi(n-1, aux_rod, to_rod, from_rod)

# Testing the function with 3 disks


tower_of_hanoi(3, 'A', 'C', 'B')

Output:

Move disk 1 from A to C


Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Result:

Hence, the implementation of Tower of Hanoi concept using python is written and
executed successfully.
3. B) Write a Program to implement Travelling Salesman Problem using Python.

Aim:

To write a python program for implementing Travelling Salesman Problem.

Program:
# program to implement traveling salesman
# problem using naive approach.
from sys import maxsize
from itertools import permutations
V=4
# implementation of traveling Salesman Problem
def travellingSalesmanProblem(graph, s):
# store all vertex apart from source vertex
vertex = []
for i in range(V):
if i != s:
[Link](i)
# store minimum weight
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
# store current Path weight(cost)
current_pathweight = 0
# compute current path weight
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
# update minimum
min_path = min(min_path, current_pathweight)
return min_path

# Driver Code
if __name__ == "__main__":
# matrix representation of graph
graph = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))

Output:
20

Result:

Hence, the implementation of Travelling Salesman Problem using python is written


and executed successfully.
4. Write a Program to implement Greedy Best First Search using Python.

Aim:

To write a python program for implementing Greedy Best First Search.

Program:
import heapq

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


open_list = [(heuristic[start], start)]
closed_set = set()

while open_list:
_, current_node = [Link](open_list)

if current_node == goal:
return True # Path found

closed_set.add(current_node)

for neighbor, _ in graph[current_node]:


if neighbor not in closed_set:
[Link](open_list, (heuristic[neighbor], neighbor))

return False # No path found

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

heuristic = {
'A': 10,
'B': 7,
'C': 5,
'D': 8,
'E': 3,
'F': 0
}

start_node = 'A'
goal_node = 'F'
path_found = greedy_best_first_search(graph, start_node, goal_node, heuristic)

if path_found:
print("Path found from", start_node, "to", goal_node)
else:
print("No path found from", start_node, "to", goal_node)

Output:

Path found from A to F

Result:

Hence, the implementation of Greedy Best First Search using python is written and
executed successfully.
5. Write a Program to implement A*Search Algorithm using Python.

Aim:

To write a python program for implementing A* Search Algorithm.

Program:
from collections import deque

class Graph:
# example of adjacency list (or rather map)
# adjacency_list = {
# 'A': [('B', 1), ('C', 3), ('D', 7)],
# 'B': [('D', 5)],
# 'C': [('D', 12)]
#}

def __init__(self, adjacency_list):


self.adjacency_list = adjacency_list

def get_neighbors(self, v):


return self.adjacency_list[v]

# heuristic function with equal values for all nodes


def h(self, n):
H={
'A': 1,
'B': 1,
'C': 1,
'D': 1
}

return H[n]

def a_star_algorithm(self, start_node, stop_node):


# open_list is a list of nodes which have been visited, but who's neighbors
# haven't all been inspected, starts off with the start node
# closed_list is a list of nodes which have been visited
# and who's neighbors have been inspected
open_list = set([start_node])
closed_list = set([])

# g contains current distances from start_node to all other nodes


# the default value (if it's not found in the map) is +infinity
g = {}

g[start_node] = 0
# parents contains an adjacency map of all nodes
parents = {}
parents[start_node] = start_node

while len(open_list) > 0:


n = None

# find a node with the lowest value of f() - evaluation function


for v in open_list:
if n == None or g[v] + self.h(v) < g[n] + self.h(n):
n = v;

if n == None:
print('Path does not exist!')
return None

# if the current node is the stop_node


# then we begin reconstructin the path from it to the start_node
if n == stop_node:
reconst_path = []

while parents[n] != n:
reconst_path.append(n)
n = parents[n]

reconst_path.append(start_node)

reconst_path.reverse()

print('Path found: {}'.format(reconst_path))


return reconst_path

# for all neighbors of the current node do


for (m, weight) in self.get_neighbors(n):
# if the current node isn't in both open_list and closed_list
# add it to open_list and note n as it's parent
if m not in open_list and m not in closed_list:
open_list.add(m)
parents[m] = n
g[m] = g[n] + weight

# otherwise, check if it's quicker to first visit n, then m


# and if it is, update parent data and g data
# and if the node was in the closed_list, move it to open_list
else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight
parents[m] = n

if m in closed_list:
closed_list.remove(m)
open_list.add(m)

# remove n from the open_list, and add it to closed_list


# because all of his neighbors were inspected
open_list.remove(n)
closed_list.add(n)

print('Path does not exist!')


return None
adjacency_list = {
'A': [('B', 1), ('C', 3), ('D', 7)],
'B': [('D', 5)],
'C': [('D', 12)]
}
graph1 = Graph(adjacency_list)
graph1.a_star_algorithm('A', 'D')

Output:

Path found: ['A', 'B', 'D']

['A', 'B', 'D']

Result:

Hence, the implementation of A* Search Algorithm using python is written and


executed successfully.
6. Write a Program to implement IDA*Search Algorithm using Python.

Aim:

To write a python program for implementing IDA* Search Algorithm

Program:
import math
# Define a graph with edges and their respective costs
graph = {
'A': {'B': 1, 'D': 3, 'G': 9},
'B': {'A': 1, 'C': 2},
'C': {'B': 2, 'E': 2},
'D': {'A': 3, 'E': 5, 'F': 2},
'E': {'C': 2, 'D': 5, 'F': 1},
'F': {'D': 2, 'E': 1, 'G': 3},
'G': {'A': 9, 'F': 3}
}

# Define the heuristic function (Manhattan distance)


heuristic = {
'A': 10,
'B': 7,
'C': 5,
'D': 8,
'E': 3,
'F': 2,
'G': 0
}

def ida_star(start, goal, h_func, graph):


def search(path, g, bound):
node = path[-1]
f = g + h_func[node]
if f > bound:
return f
if node == goal:
return 'FOUND'
min_cost = [Link]
for neighbor, cost in graph[node].items():
if neighbor not in path:
[Link](neighbor)
t = search(path, g + cost, bound)
if t == 'FOUND':
return 'FOUND'
if t < min_cost:
min_cost = t
[Link]()
return min_cost

bound = h_func[start]
path = [start]
while True:
t = search(path, 0, bound)
if t == 'FOUND':
return path
if t == [Link]:
return 'NOT FOUND'
bound = t

# Example usage
start_node = 'A'
goal_node = 'G'
path = ida_star(start_node, goal_node, heuristic, graph)

if path == 'NOT FOUND':


print("Path not found.")
else:
print("Path found:", ' -> '.join(path))

Output:

Path found: A -> B -> C -> E -> F -> G

Result:

Hence, the implementation of IDA* Search Algorithm using python is written and
executed successfully.
7. Write a Program to implement Alpha-Beta Pruning using Python.

Aim:

To write a python program for implementing Alpha-Beta Pruning.

Program:
# Python3 program to demonstrate
# working of Alpha-Beta Pruning

# Initial values of Alpha and Beta


MAX, MIN = 1000, -1000

# Returns optimal value for current player


#(Initially called for root and maximizer)

def minimax(depth, nodeIndex, maximizingPlayer, values, alpha, beta):


# Terminating condition. i.e
# leaf node is reached
if depth == 3:
return values[nodeIndex]
if maximizingPlayer:
best = MIN
# Recur for left and right children
for i in range(0, 2):
val = minimax(depth + 1, nodeIndex * 2 + i,False, values,
alpha, beta)
best = max(best, val)
alpha = max(alpha, best)
# Alpha Beta Pruning
if beta <= alpha:
break
return best
else:
best = MAX

# Recur for left and


# right children
for i in range(0, 2):
val = minimax(depth + 1, nodeIndex * 2 + i, True, values,
alpha, beta)
best = min(best, val)
beta = min(beta, best)
# Alpha Beta Pruning
if beta <= alpha:
break
return best
# Driver Code
if __name__ == "__main__":
values = [3, 5, 6, 9, 1, 2, 0, -1]
print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))

Output:

The optimal value is : 5

Result:

Hence, the implementation of Alpha-Beta Pruning using python is written and


executed successfully.
8. Write a Program to implement Tic-Tac-Toe game using Python.

Aim:

To write a python program for implementing Greedy Best First Search.

Program:
import os
import time

board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1

########win Flags##########
Win = 1
Draw = -1
Running = 0
Stop = 1
###########################
Game = Running
Mark = 'X'

#This Function Draws Game Board


def DrawBoard():
print(" %c | %c | %c " % (board[1],board[2],board[3]))
print("___|___|___")
print(" %c | %c | %c " % (board[4],board[5],board[6]))
print("___|___|___")
print(" %c | %c | %c " % (board[7],board[8],board[9]))
print(" | | ")

#This Function Checks position is empty or not


def CheckPosition(x):
if(board[x] == ' '):
return True
else:
return False

#This Function Checks player has won or not


def CheckWin():
global Game
#Horizontal winning condition
if(board[1] == board[2] and board[2] == board[3] and board[1] != ' '):
Game = Win
elif(board[4] == board[5] and board[5] == board[6] and board[4] != ' '):
Game = Win
elif(board[7] == board[8] and board[8] == board[9] and board[7] != ' '):
Game = Win
#Vertical Winning Condition
elif(board[1] == board[4] and board[4] == board[7] and board[1] != ' '):
Game = Win
elif(board[2] == board[5] and board[5] == board[8] and board[2] != ' '):
Game = Win
elif(board[3] == board[6] and board[6] == board[9] and board[3] != ' '):
Game=Win
#Diagonal Winning Condition
elif(board[1] == board[5] and board[5] == board[9] and board[5] != ' '):
Game = Win
elif(board[3] == board[5] and board[5] == board[7] and board[5] != ' '):
Game=Win
#Match Tie or Draw Condition
elif(board[1]!=' ' and board[2]!=' ' and board[3]!=' ' and board[4]!=' ' and
board[5]!=' ' and board[6]!=' ' and board[7]!=' ' and board[8]!=' ' and board[9]!=' '):
Game=Draw
else:
Game=Running

print("Tic-Tac-Toe Game Explained by R G Kumar")


print("Player 1 [X] --- Player 2 [O]\n")
print()
print()
print("Please Wait...")
[Link](3)
while(Game == Running):
[Link]('cls')
DrawBoard()
if(player % 2 != 0):
print("Player 1's chance")
Mark = 'X'
else:
print("Player 2's chance")
Mark = 'O'
choice = int(input("Enter the position between [1-9] where you want to mark : "))
if(CheckPosition(choice)):
board[choice] = Mark
player+=1
CheckWin()

[Link]('cls')
DrawBoard()
if(Game==Draw):
print("Game Draw")
elif(Game==Win):
player-=1
if(player%2!=0):
print("Player 1 Won")
else:
print("Player 2 Won")

Output:

Tic-Tac-Toe Game Explained by R G Kumar


Player 1 [X] --- Player 2 [O]

Please Wait...
| |
___|___|___
| |
___|___|___
| |
| |
Player 1's chance

Enter the position between [1-9] where you want to mark : 3


| |X
___|___|___
| |
___|___|___
| |
| |
Player 2's chance

Enter the position between [1-9] where you want to mark : 4


| |X
___|___|___
O| |
___|___|___
| |
| |
Player 1's chance

Enter the position between [1-9] where you want to mark : 5


| |X
___|___|___
O|X|
___|___|___
| |
| |
Player 2's chance

Enter the position between [1-9] where you want to mark : 6


| |X
___|___|___
O|X|O
___|___|___
| |
| |
Player 1's chance

Enter the position between [1-9] where you want to mark : 7


| |X
___|___|___
O|X|O
___|___|___
X| |
| |
Player 1 Won

Result:

Hence, the implementation of Tic-Tac-Toe game using python is written and executed
successfully.
9. Write a Program to implement Natural Deduction System in Python.

Aim:

To write a python program for implementing Natural Deduction System.

Program:

class NDSystem:
def __init__(self):
[Link] = []
[Link] = []
def assume(self, statement):
[Link](statement)
def apply_and_intro(self, premise1, premise2):
conclusion = f"({premise1} ∧ {premise2})"
[Link](conclusion)
def apply_and_elim(self, conjunction):
premise1 = [Link]('∧')[0].strip()
premise2 = [Link]('∧')[1].strip()
[Link](premise1)
[Link](premise2)
def prove(self, statement):
if statement in [Link]:
print("The statement is provable.")
else:
print("The statement is not provable.")

# Example usage
nd_system = NDSystem()
# Assume premises
nd_system.assume("A")
nd_system.assume("B")
# Apply rules
nd_system.apply_and_intro("A", "B")
# Prove a statement
nd_system.prove("(A ∧ B)")

Output:

The statement is provable.

Result:

Hence, the implementation of Natural Deduction System using python is written and
executed successfully.
10. Write a Program to implement Axiomatic System in Python.

Aim:

To write a python program for implementing Axiomatic System.

Program:
class AxiomaticSystem:
def __init__(self):
[Link] = []

def add_axiom(self, axiom):


[Link](axiom)

def prove(self, statement):


if statement in [Link]:
print("The statement is provable.")
else:
print("The statement is not provable.")

# Example usage
ax_system = AxiomaticSystem()

# Add axioms
ax_system.add_axiom("A")
ax_system.add_axiom("(A → A)")

# Prove a statement
ax_system.prove("A")
ax_system.prove("(A → A)")
ax_system.prove("B")

Output:

The statement is provable.


The statement is provable.
The statement is not provable.

Result:

Hence, the implementation of Axiomatic System using python is written and executed
successfully.
11. Write a Program to implement KR using Semantic Network in Python.

Aim:

To write a python program for implementing KR using Semantic Network.

Program:

class Node:
def __init__(self, name):
[Link] = name
[Link] = []

def add_neighbor(self, neighbor):


[Link](neighbor)
# Example usage
# Create nodes
john = Node("John")
mary = Node("Mary")
likes = Node("likes")
pizza = Node("pizza")

# Add neighbors
john.add_neighbor(likes)
likes.add_neighbor(mary)
likes.add_neighbor(pizza)

# Traverse the network


print(f"{[Link]} likes:")
for neighbor in [Link]:
print("-", [Link])

Output:
John likes:
- Mary
- pizza

Result:

Hence, the implementation of KR using Semantic Network in python is written and


executed successfully.
12. Write a Program to implement Conceptual Dependency Theory in Python.

Aim:

To write a python program for implementing Conceptual Dependency Theory.

Program:
class Concept:
def __init__(self, name):
[Link] = name
[Link] = {}
def set_attribute(self, attribute, value):
[Link][attribute] = value
class Relation:
def __init__(self, relation_type, from_concept, to_concept):
self.relation_type = relation_type
self.from_concept = from_concept
self.to_concept = to_concept

# Example usage
# Create concepts
cat = Concept("cat")
dog = Concept("dog")
animal = Concept("animal")
# Set attributes
cat.set_attribute("color", "black")
dog.set_attribute("color", "brown")
# Create relations
rel1 = Relation("is_a", cat, animal)
rel2 = Relation("is_a", dog, animal)
# Print information
print(f"The {[Link]} is {[Link]['color']}")
print(f"The {[Link]} is {[Link]['color']}")
print(f"The {[Link]} is an {rel1.to_concept.name}")
print(f"The {[Link]} is an {rel2.to_concept.name}")

Output:

The cat is black


The dog is brown
The cat is an animal
The dog is an animal

Result:

Hence, the implementation of Conceptual Dependency Theory using python is written


and executed successfully.

You might also like