MATU RAM INSTITUTE OF ENGINEERING
AND MANAGEMENT
Practical File of
Artificial Intelligence
Submitted to: Submitted by:
Mrs. Jyoti Ahlawat Saloni Khatri
Assistant Professor 5627 (B.Tech CSE)
CSE Department 6th Semester
Index
1 Write a program to print ‘HELLO WORLD’ in python
2 Write a program to add two numbers with user input
3 Write a program to swap two variables
4 Write a program to check if a number is positive, negative or 0
5 Write a program to check if a number is even or odd
6 Write a program to check leap year
7 Write a program to check prime number
8 Write a program to find factorial of number using recursion
9 Write a program to create Pyramid Patterns
10 Write a program to implement Inheritance
11 Write a program to implement python List operation
12 Write a program in python to create class and object
13 Write a program in python to implement polymorphism
14 Write a program to implement breadth first search using python
15 Write a program to implement depth first search using python
16 Write a program to implement water jug problem using python
17 Write a program to implement travelling salesman problem in python
18 Write a program to implement Tower of Hanoi using python
19 Write a program to implement 8 Queen Problem using python
20 Write a python program to implement MATPLOT Library
21 Write a python program to implement MATPLOT LABEL
22 Write a python program to implement MATPLOT BAR GRAPH
1. Write a program to print ‘HELLO WORLD’ in python.
# This program prints 'HELLO WORLD'
print("Hello, World!")
Output:
Hello, World!
2. Write a program to add two numbers with user input.
# Python program to add two numbers
num1 = 15
num2 = 12
# Adding two nos
sum = num1 + num2
# printing values
print("Sum of", num1, "and", num2 , "is", sum)
Output:
Sum of 15 and 12 is 27
3. Write a program to swap two variables.
# Python program to demonstrate
# swapping of two variables
x = 10
y = 50
# Swapping of two variables
# Using third variable
temp = x
x = y
y = temp
print("Value of x:", x)
print("Value of y:", y)
Output:
Value of x: 50
Value of y: 10
4. Write a program to check if a number is positive,
negative or 0.
# Python program to check whether the number is positive,
negative or #equal to zero
def check(n):
# if the number is positive
if n > 0:
print("Positive")
# if the number is negative
elif n < 0:
print("Negative")
# if the number is equal to
# zero
else:
print("Equal to zero")
# Driver Code
check(5)
check(0)
check(-5)
Output:
Positive
Equal to zero
Negative
5. Write a program to check if a number is even or odd.
x = 24
if x % 24 == 0:
print(x,"Is Even Number")
else:
print(x, "Is Odd Number")
y = 19
if y % 19 == 0:
print(y,"Is Even Number")
else:
print(y, "Is Odd Number")
Output:
24 Is Even Number
19 Is Even Number
6. Write a program to check leap year.
def is_leap_year_modulo(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# Example
year_to_check = 2024
result_modulo = is_leap_year_modulo(year_to_check)
print(f"{year_to_check} is a leap year: {result_modulo}")
Output:
2024 is a leap year: True
7. Write a program to check prime number.
num = 11
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n // 2
for i in range(2, (num//2)+1):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output:
11 is a prime number
8. Write a program to find factorial of number using
recursion.
# Python 3 program to find factorial of given number
def factorial(n):
# Checking the number
# is 1 or 0 then
# return 1
# other wise return
# factorial
if (n==1 or n==0):
return 1
else:
return (n * factorial(n - 1))
# Driver Code
num = 5;
print("number : ",num)
print("Factorial : ",factorial(num))
Output:
number : 5
Factorial : 120
9. Write a program to create Pyramid Patterns.
# Function to print full pyramid pattern
def full_pyramid(n):
for i in range(1, n + 1):
# Print leading spaces
for j in range(n - i):
print(" ", end="")
# Print asterisks for the current row
for k in range(1, 2*i):
print("*", end="")
Output:
*
***
*****
*******
*********
10.Write a program to implement Inheritance.
class Animal:
# attribute and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# new method in subclass
def display(self):
# access name attribute of superclass using self
print("My name is ", self.name)
# create an object of the subclass
labrador = Dog()
# access superclass attribute and method
labrador.name = " Dollar "
labrador.eat()
# call subclass method
labrador.display()
Output:
I can eat
My name is Dollar
11.Write a program to implement python List operation.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Output:
['cherry', 'orange', 'kiwi']
['cherry', 'orange', 'kiwi', 'melon', 'mango']
12.Write a program in python to create class and object.
class Person:
def init (self, name, age):
self.name = name
self.age = age
p1 = Person("Saloni", 20)
print(p1.name)
print(p1.age
Output:
Saloni
20
13.Write a program in python to implement polymorphism.
class Car:
def init (self, brand, model):
self.brand = brand
self.model = model
def move(self):
print(" C R E T A ")
class Boat:
def init (self, brand, model):
self.brand = brand
self.model = model
def move(self):
print(" H Y U N D A I ")
class Plane:
def init (self, brand, model):
self.brand = brand
self.model = model
def move(self):
print(2022)
car1 = Car("Ford", "Mustang") #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class
for x in (car1, boat1, plane1):
x.move()
Output:
C R E T A
H Y U N D A I
2022
14.Write a program to implement breadth first search using
python.
# Python Program to print BFS traversal from a given source vertex.
BFS(int s) traverses vertices reachable from s.
from collections import defaultdict
# This class represents a directed graph using adjacency list
representation
class Graph:
# Constructor
def __init__(self):
# Default dictionary to store graph
self.graph = defaultdict(list)
# Function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False] * (max(self.graph) + 1)
# Create a queue for BFS
queue = []
# Mark the source node as visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# Dequeue a vertex from queue and print it
s = queue.pop(0)
print(s, end=" ")
# Get all adjacent vertices of the dequeued vertex s.
# If an adjacent has not been visited, then mark it
visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code
if __name__ == '__main__':
# Create a graph given in the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is Breadth First Traversal"
" (starting from vertex 2)")
g.BFS(2)
Output:
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1
15.Write a program to implement depth first search using
python.
# Python program to print DFS traversal from a given graph
from collections import defaultdict
# This class represents a directed graph using adjacency list
representation
class Graph:
# Constructor
def __init__(self):
# Default dictionary to store graph
self.graph = defaultdict(list)
# Function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(self, v, visited):
# Mark the current node as visited and print it
visited.add(v)
print(v, end=' ')
# Recur for all the vertices adjacent to this vertex
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
# The function to do DFS traversal. It uses recursive DFSUtil()
def DFS(self, v):
# Create a set to store visited vertices
visited = set()
# Call the recursive helper function to print DFS traversal
self.DFSUtil(v, visited)
# Driver's code
if __name__ == "__main__":
g = Graph()
g.addEdge(4, 5)
g.addEdge(4, 6)
g.addEdge(5, 6)
g.addEdge(6, 4)
g.addEdge(6, 7)
g.addEdge(7, 7)
print("Following is Depth First Traversal (starting from vertex
6)")
# Function call
g.DFS(6)
Output:
Following is Depth First Traversal (starting from vertex 6)
6 4 5 7
16.Write a program to implement water jug problem using
python.
#Python program to solve water jug problem
from collections import deque
def BFS(a, b, target):
m = {}
isSolvable = False
path = []
q = deque()
q.append((0, 0))
while (len(q) > 0):
u = q.popleft() # If this state is already visited
if ((u[0], u[1]) in m):
continue
if ((u[0] > a or u[1] > b or
u[0] < 0 or u[1] < 0)):
continue
# Filling the vector for constructing the solution path
path.append([u[0], u[1]])
# Marking current state as visited
m[(u[0], u[1])] = 1
# If we reach solution state, put ans=1
if (u[0] == target or u[1] == target):
isSolvable = True
if (u[0] == target):
if (u[1] != 0):
# Fill final state
path.append([u[0], 0])
else:
if (u[0] != 0):
# Fill final state
path.append([0, u[1]])
# Print the solution path
sz = len(path)
for i in range(sz):
print("(", path[i][0], ",",
path[i][1], ")")
break
# If we have not reached final state then, start developing
intermediate states to reach solution state
q.append([u[0], b]) # Fill Jug2
q.append([a, u[1]]) # Fill Jug1
for ap in range(max(a, b) + 1):
# Pour amount ap from Jug2 to Jug1
c = u[0] + ap
d = u[1] - ap
# Check if this state is possible or not
if (c == a or (d == 0 and d >= 0)):
q.append([c, d])
# Pour amount ap from Jug 1 to Jug2
c = u[0] - ap
d = u[1] + ap
# Check if this state is possible or not
if ((c == 0 and c >= 0) or d == b):
q.append([c, d])
# Empty Jug2
q.append([a, 0])
# Empty Jug1
q.append([0, b])
# No, solution exists if ans=0
if (not isSolvable):
print("No solution")
# Driver code
if __name__ == '__main__':
Jug1, Jug2, target = 4, 3, 2
print("Path from initial state "
"to solution state ::")
BFS(Jug1, Jug2, target)
Output:
( 0 , 0 )
( 0 , 3 )
( 4 , 0 )
( 4 , 3 )
( 3 , 0 )
( 1 , 3 )
( 3 , 3 )
( 4 , 2 )
( 0 , 2 )
17.Write a program to implement travelling salesman problem
in python.
# Python3 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:
vertex.append(i)
# store minimum weight Hamiltonian Cycle
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:
80
18.Write a program to implement Tower of Hanoi using python.
# Recursive Python function to solve the tower of hanoi
def TowerOfHanoi(n , source, destination, auxiliary):
if n==1:
print ("Move disk 1 from source",source,"to
destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to
destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
# Driver code
n = 4
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
Output:
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
Move disk 3 from source A to destination C
Move disk 1 from source B to destination A
Move disk 2 from source B to destination C
Move disk 1 from source A to destination C
Move disk 4 from source A to destination B
Move disk 1 from source C to destination B
Move disk 2 from source C to destination A
Move disk 1 from source B to destination A
Move disk 3 from source C to destination B
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
19.Write a program to implement 8 Queen Problem using
python.
# Python program to print the path from root node to destination node
for N*N-1 puzzle algorithm using Branch and Bound
#The solution assumes that instance of puzzle is solvable
# Importing copy for deepcopy function
import copy
# Importing the heap functions from python library for Priority Queue
from heapq import heappush, heappop
# This variable can be changed to change the program from 8
puzzle(n=3) to 15 puzzle(n=4) to 24 puzzle(n=5)...
n = 3
# bottom, left, top, right
row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]
# A class for Priority Queue
class priorityQueue:
# Constructor to initialize a Priority Queue
def __init__(self):
self.heap = []
# Inserts a new key 'k'
def push(self, k):
heappush(self.heap, k)
# Method to remove minimum element from Priority Queue
def pop(self):
return heappop(self.heap)
# Method to know if the Queue is empty
def empty(self):
if not self.heap:
return True
else:
return False
# Node structure
class node:
def __init__(self, parent, mat, empty_tile_pos,
cost, level):
# Stores the parent node of the current node helps in tracing
path when the answer is found
self.parent = parent
# Stores the matrix
self.mat = mat
# Stores the position at which the empty space tile exists in
the matrix
self.empty_tile_pos = empty_tile_pos
# Stores the number of misplaced tiles
self.cost = cost
# Stores the number of moves so far
self.level = level
# This method is defined so that the priority queue is formed
based on the cost variable of the objects
def __lt__(self, nxt):
return self.cost < nxt.cost
# Function to calculate the number of misplaced tiles ie. number of
non-blank tiles not in their goal position
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:
# Copy data from parent matrix to current matrix
new_mat = copy.deepcopy(mat)
# Move tile by 1 position
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]
# Set number of misplaced tiles
cost = calculateCost(new_mat, final)
new_node = node(parent, new_mat, new_empty_tile_pos,
cost, level)
return new_node
# Function to print the N x N matrix
def printMatrix(mat):
for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")
print()
# Function to check if (x, y) is a valid matrix coordinate
def isSafe(x, y):
return x >= 0 and x < n and y >= 0 and y < n
# Print path from root node to destination node
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
# Function to solve N*N - 1 puzzle algorithm using Branch and Bound.
empty_tile_pos is the blank tile position in the initial state.
def solve(initial, empty_tile_pos, final):
# Create a priority queue to store live nodes of search tree
pq = priorityQueue()
# Create the root node
cost = calculateCost(initial, final)
root = node(None, initial,
empty_tile_pos, cost, 0)
# Add root to list of live nodes
pq.push(root)
# Finds a live node with least cost, add its children to list of
live nodes and finally deletes it from the list.
while not pq.empty():
# Find a live node with least estimated cost and delete it
from the list of live nodes
minimum = pq.pop()
# If minimum is the answer node
if minimum.cost == 0:
# Print the path from root to destination;
printPath(minimum)
return
# Generate all possible children
for i in range(4):
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]):
# Create a child node
child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)
# Add child to list of live nodes
pq.push(child)
# Driver Code
# Initial configuration
# Value 0 is used for empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
# Solvable Final configuration Value 0 is used for empty space
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
# Blank tile coordinates in initial configuration
empty_tile_pos = [ 1, 2 ]
# Function call to solve the puzzle
solve(initial, empty_tile_pos, final)
Output:
1 2 3
5 0 6
7 8 4
1 2 3
5 8 6
7 0 4
1 2 3
5 8 6
0 7 4
20.Write a python program to implement MATPLOT Library.
# a Python program to implement MATPLOT Library
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linestyle = 'dotted')
plt.show()
Output:
21.Write a python program to implement MATPLOT LABEL.
# Python program to implement MATPLOT LABEL
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.xlabel(" ENGINEERING ")
plt.ylabel(" M.D.U ")
plt.show()
Output:
22.Write a python program to implement MATPLOT BAR GRAPH.
# Python program to implement MATPLOT BAR GRAPH
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.xlabel(" PATIENT ")
plt.ylabel(" COVID CASES ")
plt.bar(x,y)
plt.show()
Output: