Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

St.

Vincent Pallotti College of Engineering &


Technology

Department of Information Technology

Academic Year : 2022-23

PRACTICAL HANDBOOK

Program : Information Technology


Course : Artificial Intelligence & Machine Learning
Semester : 6th Sem IT

EXPERIMENT NO. 1

1|Page
NAME OF THE EXPERIMENT: To Study of artificial Intelligence

LEARNING OBJECTIVE : To learn the concept of artificial Intelligence


PRE - REQUISITE: Python Programming

BASIC CONCEPTS:

Introduction to Artificial Intelligence (AI)-

In today's world, technology is growing very fast, and we are getting in touch with different new
technologies day by day.

Here, one of the booming technologies of computer science is Artificial Intelligence which is
ready to create a new revolution in the world by making intelligent machines. The Artificial
Intelligence is now all around us. It is currently working with a variety of subfields, ranging from
general to specific, such as self-driving cars, playing chess, proving theorems, playing music,
Painting, etc.

AI is one of the fascinating and universal fields of Computer science which has a great scope in
future. AI holds a tendency to cause a machine to work as a human.

Artificial Intelligence is composed of two words Artificial and Intelligence, where Artificial
defines "man-made," and intelligence defines "thinking power", hence AI means "a man-made
thinking power."

So, we can define AI as:

"It is a branch of computer science by which we can create intelligent machines which can
behave like a human, think like humans, and able to make decisions."

Artificial Intelligence exists when a machine can have human based skills such as learning,
reasoning, and solving problems

With Artificial Intelligence you do not need to preprogram a machine to do some work, despite
that you can create a machine with programmed algorithms which can work with own
intelligence, and that is the awesomeness of AI.

It is believed that AI is not a new technology, and some people says that as per Greek myth,
there were Mechanical men in early days which can work and behave like humans.

Why Artificial Intelligence?

2|Page
Before Learning about Artificial Intelligence, we should know that what is the importance of AI
and why should we learn it. Following are some main reasons to learn about AI:

o With the help of AI, you can create such software or devices which can solve real-world
problems very easily and with accuracy such as health issues, marketing, traffic issues,
etc.
o With the help of AI, you can create your personal virtual Assistant, such as Cortana,
Google Assistant, Siri, etc.
o With the help of AI, you can build such Robots which can work in an environment where
survival of humans can be at risk.
o AI opens a path for other new technologies, new devices, and new Opportunities.

History of Artificial Intelligence

Artificial Intelligence is not a new word and not a new technology for researchers. This
technology is much older than you would imagine. Even there are the myths of Mechanical men
in Ancient Greek and Egyptian Myths. Following are some milestones in the history of AI which
defines the journey from the AI generation to till date development.

Maturation of Artificial Intelligence (1943-1952)

3|Page
o Year 1943: The first work which is now recognized as AI was done by Warren
McCulloch and Walter pits in 1943. They proposed a model of artificial neurons.
o Year 1949: Donald Hebb demonstrated an updating rule for modifying the connection
strength between neurons. His rule is now called Hebbian learning.
o Year 1950: The Alan Turing who was an English mathematician and pioneered Machine
learning in 1950. Alan Turing publishes "Computing Machinery and Intelligence" in
which he proposed a test. The test can check the machine's ability to exhibit intelligent
behavior equivalent to human intelligence, called a Turing test.

The birth of Artificial Intelligence (1952-1956)

o Year 1955: An Allen Newell and Herbert A. Simon created the "first artificial
intelligence program"Which was named as "Logic Theorist". This program had proved
38 of 52 Mathematics theorems, and find new and more elegant proofs for some
theorems.
o Year 1956: The word "Artificial Intelligence" first adopted by American Computer
scientist John McCarthy at the Dartmouth Conference. For the first time, AI coined as an
academic field.

At that time high-level computer languages such as FORTRAN, LISP, or COBOL were
invented. And the enthusiasm for AI was very high at that time.

The golden years-Early enthusiasm (1956-1974)

o Year 1966: The researchers emphasized developing algorithms which can solve
mathematical problems. Joseph Weizenbaum created the first chatbot in 1966, which was
named as ELIZA.
o Year 1972: The first intelligent humanoid robot was built in Japan which was named as
WABOT-1.

The first AI winter (1974-1980)

o The duration between years 1974 to 1980 was the first AI winter duration. AI winter
refers to the time period where computer scientist dealt with a severe shortage of funding
from government for AI researches.
o During AI winters, an interest of publicity on artificial intelligence was decreased.

4|Page
A boom of AI (1980-1987)

o Year 1980: After AI winter duration, AI came back with "Expert System". Expert
systems were programmed that emulate the decision-making ability of a human expert.
o In the Year 1980, the first national conference of the American Association of Artificial
Intelligence was held at Stanford University.

The second AI winter (1987-1993)

o The duration between the years 1987 to 1993 was the second AI Winter duration.
o Again Investors and government stopped in funding for AI research as due to high cost
but not efficient result. The expert system such as XCON was very cost effective.

The emergence of intelligent agents (1993-2011)

o Year 1997: In the year 1997, IBM Deep Blue beats world chess champion, Gary
Kasparov, and became the first computer to beat a world chess champion.
o Year 2002: for the first time, AI entered the home in the form of Roomba, a vacuum
cleaner.
o Year 2006: AI came in the Business world till the year 2006. Companies like Facebook,
Twitter, and Netflix also started using AI.

Deep learning, big data and artificial general intelligence (2011-present)

o Year 2011: In the year 2011, IBM's Watson won jeopardy, a quiz show, where it had to
solve the complex questions as well as riddles. Watson had proved that it could
understand natural language and can solve tricky questions quickly.
o Year 2012: Google has launched an Android app feature "Google now", which was able
to provide information to the user as a prediction.
o Year 2014: In the year 2014, Chatbot "Eugene Goostman" won a competition in the
infamous "Turing test."
o Year 2018: The "Project Debater" from IBM debated on complex topics with two master
debaters and also performed extremely well.
o Google has demonstrated an AI program "Duplex" which was a virtual assistant and
which had taken hairdresser appointment on call, and lady on other side didn't notice that
she was talking with the machine.

5|Page
Now AI has developed to a remarkable level. The concept of Deep learning, big data, and data
science are now trending like a boom. Nowadays companies like Google, Facebook, IBM, and
Amazon are working with AI and creating amazing devices. The future of Artificial Intelligence
is inspiring and will come with high intelligence.

Goals of Artificial Intelligence

Following are the main goals of Artificial Intelligence:

1. Replicate human intelligence


2. Solve Knowledge-intensive tasks
3. An intelligent connection of perception and action
4. Building a machine which can perform tasks that requires human intelligence such as:
o Proving a theorem
o Playing chess
o Plan some surgical operation
o Driving a car in traffic
5. Creating some system which can exhibit intelligent behavior, learn new things by itself,
demonstrate, explain, and can advise to its user.

Advantages of Artificial Intelligence

Following are some main advantages of Artificial Intelligence:

o High Accuracy with less errors: AI machines or systems are prone to less errors and
high accuracy as it takes decisions as per pre-experience or information.
o High-Speed: AI systems can be of very high-speed and fast-decision making, because of
that AI systems can beat a chess champion in the Chess game.
o High reliability: AI machines are highly reliable and can perform the same action
multiple times with high accuracy.
o Useful for risky areas: AI machines can be helpful in situations such as defusing a
bomb, exploring the ocean floor, where to employ a human can be risky.
o Digital Assistant: AI can be very useful to provide digital assistant to the users such as
AI technology is currently used by various E-commerce websites to show the products as
per customer requirement.

6|Page
o Useful as a public utility: AI can be very useful for public utilities such as a self-driving
car which can make our journey safer and hassle-free, facial recognition for security
purpose, Natural language processing to communicate with the human in human-
language, etc.

Disadvantages of Artificial Intelligence

Every technology has some disadvantages, and thesame goes for Artificial intelligence. Being so
advantageous technology still, it has some disadvantages which we need to keep in our mind
while creating an AI system. Following are the disadvantages of AI:

o High Cost: The hardware and software requirement of AI is very costly as it requires lots
of maintenance to meet current world requirements.
o Can't think out of the box: Even we are making smarter machines with AI, but still they
cannot work out of the box, as the robot will only do that work for which they are trained,
or programmed.
o No feelings and emotions: AI machines can be an outstanding performer, but still it does
not have the feeling so it cannot make any kind of emotional attachment with human, and
may sometime be harmful for users if the proper care is not taken.
o Increase dependency on machines: With the increment of technology, people are
getting more dependent on devices and hence they are losing their mental capabilities.
o No Original Creativity: As humans are so creative and can imagine some new ideas but
still AI machines cannot beat this power of human intelligence and cannot be creative and
imaginative.

Types of Artificial Intelligence:

Artificial Intelligence can be divided in various types, there are mainly two types of main
categorization which are based on capabilities and based on functionally of AI. Following is flow
diagram which explain the types of AI.

7|Page
AI type-1: Based on Capabilities

1. Weak AI or Narrow AI:

o Narrow AI is a type of AI which is able to perform a dedicated task with intelligence.The


most common and currently available AI is Narrow AI in the world of Artificial
Intelligence.
o Narrow AI cannot perform beyond its field or limitations, as it is only trained for one
specific task. Hence it is also termed as weak AI. Narrow AI can fail in unpredictable
ways if it goes beyond its limits.
o Apple Siriis a good example of Narrow AI, but it operates with a limited pre-defined
range of functions.
o IBM's Watson supercomputer also comes under Narrow AI, as it uses an Expert system
approach combined with Machine learning and natural language processing.
o Some Examples of Narrow AI are playing chess, purchasing suggestions on e-commerce
site, self-driving cars, speech recognition, and image recognition.

2. General AI:

o General AI is a type of intelligence which could perform any intellectual task with
efficiency like a human.
o The idea behind the general AI to make such a system which could be smarter and think
like a human by its own.

8|Page
o Currently, there is no such system exist which could come under general AI and can
perform any task as perfect as a human.
o The worldwide researchers are now focused on developing machines with General AI.
o As systems with general AI are still under research, and it will take lots of efforts and
time to develop such systems.

3. Super AI:

o Super AI is a level of Intelligence of Systems at which machines could surpass human


intelligence, and can perform any task better than human with cognitive properties. It is
an outcome of general AI.
o Some key characteristics of strong AI include capability include the ability to think, to
reason,solve the puzzle, make judgments, plan, learn, and communicate by its own.
o Super AI is still a hypothetical concept of Artificial Intelligence. Development of such
systems in real is still world changing task.

Artificial Intelligence type-2: Based on functionality

1. Reactive Machines

o Purely reactive machines are the most basic types of Artificial Intelligence.
o Such AI systems do not store memories or past experiences for future actions.

9|Page
o These machines only focus on current scenarios and react on it as per possible best
action.
o IBM's Deep Blue system is an example of reactive machines.
o Google's AlphaGo is also an example of reactive machines.

2. Limited Memory

o Limited memory machines can store past experiences or some data for a short period of
time.
o These machines can use stored data for a limited time period only.
o Self-driving cars are one of the best examples of Limited Memory systems. These cars
can store recent speed of nearby cars, the distance of other cars, speed limit, and other
information to navigate the road.

3. Theory of Mind

o Theory of Mind AI should understand the human emotions, people, beliefs, and be able
to interact socially like humans.
o This type of AI machines are still not developed, but researchers are making lots of
efforts and improvement for developing such AI machines.

4. Self-Awareness

o Self-awareness AI is the future of Artificial Intelligence. These machines will be super


intelligent, and will have their own consciousness, sentiments, and self-awareness.
o These machines will be smarter than human mind.
o Self-Awareness AI does not exist in reality still and it is a hypothetical concept.

FURTHER READINGS:
1. https://www.javatpoint.com/artificial-intelligence-ai
2. https://www.red-gate.com/simple-talk/development/data-science-development/introduction-to-
artificial-intelligence/
3. https://www.geeksforgeeks.org/artificial-intelligence-an-introduction/
4. https://www.simplilearn.com/tutorials/artificial-intelligence-tutorial/what-is-artificial-
intelligence
5. https://www.guru99.com/artificial-intelligence-tutorial.html

10 | P a g e
Experiment No: 2

Name Of The Experiment: Write a program in python to implement Depth First Search
for traversing a graph

LEARNING OBJECTIVE : To learn the concept DFS graph traversing using python

PRE – REQUISITE: Graph Traversal Techniques


Theory:
Depth First Search (DFS)
The DFS algorithm is a recursive algorithm that uses the idea of backtracking. It involves
exhaustive searches of all the nodes by going ahead, if possible, else by backtracking.
Here, the word backtrack means that when you are moving forward and there are no more nodes
along the current path, you move backwards on the same path to find nodes to traverse. All the
nodes will be visited on the current path till all the unvisited nodes have been traversed after
which the next path will be selected.
This recursive nature of DFS can be implemented using stacks. The basic idea is as follows:
Pick a starting node and push all its adjacent nodes into a stack.
Pop a node from stack to select the next node to visit and push all its adjacent nodes into a stack.
Repeat this process until the stack is empty. However, ensure that the nodes that are visited are
marked. This will prevent you from visiting the same node more than once. If you do not mark
the nodes that are visited and you visit the same node more than once, you may end up in an
infinite loop.

Algorithm:
o Generate a node stack and visit an array.
o Insert the stack's root.
o Run a loop until the stack is not empty.
o Print the element after removing it from the stack.
o Mark the current node and add it to the stack for every adjacent and unvisited node.

Program:
def add_node(v):
if v in graph:
print(v,"Node already present")
else:
graph[v]=[]

def add_edge(v1,v2):
if v1 not in graph:
print(v1,"Node is not present")

11 | P a g e
elif v2 not in graph:
print(v2,"Node is not present in graph")
else:
graph[v1].append(v2)

def dfs(node,graph):
visited=set()
if node not in graph:
print(node,"Node not in graph");
return
stack=[]
stack.append(node)
while stack:
current=stack.pop()
if current not in visited:
print(current)
visited.add(current)
for i in graph [current]:
stack.append(i)

graph={}
add_node("A")
add_node("B")
add_node("C")
add_node("D")
add_node("E")
add_edge("A","B")
add_edge("B","E")
add_edge("A","C")
add_edge("A","D")
add_edge("B","D")
add_edge("C","D")
add_edge("E","D")
print(graph)
print("DFS traversal of given graph is-")
dfs("A",graph)

Output:
{'A': ['B', 'C', 'D'], 'B': ['E', 'D'], 'C': ['D'], 'D': [], 'E': ['D']}
DFS traversal of given graph is-

12 | P a g e
A
D
C
B
E

FURTHER READINGS:
1. https://www.javatpoint.com/depth-first-search-algorithm
2. https://www.programiz.com/dsa/graph-dfs
3 https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
4. https://www.tutorialspoint.com/data_structures_algorithms/depth_first_traversal.htm
5. https://www.simplilearn.com/tutorials/data-structure-tutorial/dfs-algorithm

13 | P a g e
Experiment No:3

NAME OF THE EXPERIMENT: Write a program in python to implement Breadth


First Search for traversing a graph

LEARNING OBJECTIVE : To learn the concept DFS graph traversing using python

PRE – REQUISITE: Graph Traversal Techniques

BASIC CONCEPTS :

Theory:

Breadth First Search or BFS for a Graph-


Breadth-first search is a graph traversal algorithm that starts traversing the graph from the root
node and explores all the neighboring nodes. Then, it selects the nearest node and explores all the
unexplored nodes. While using BFS for traversal, any node in the graph can be considered as the
root node.
There are many ways to traverse the graph, but among them, BFS is the most commonly used
approach. It is a recursive algorithm to search all the vertices of a tree or graph data structure.
BFS puts every vertex of the graph into two categories - visited and non-visited. It selects a
single node in a graph and, after that, visits all the nodes adjacent to the selected node.
Applications of BFS algorithm
The applications of breadth-first-algorithm are given as follows -
1. BFS can be used to find the neighboring locations from a given source location.
2. In a peer-to-peer network, BFS algorithm can be used as a traversal method to find all the
neighboring nodes. Most torrent clients, such as BitTorrent, uTorrent, etc. employ this
process to find "seeds" and "peers" in the network.
3. BFS can be used in web crawlers to create web page indexes. It is one of the main
algorithms that can be used to index web pages. It starts traversing from the source page
and follows the links associated with the page. Here, every web page is considered as a
node in the graph.
4. BFS is used to determine the shortest path and minimum spanning tree.
5. BFS is also used in Cheney's technique to duplicate the garbage collection.
6. It can be used in ford-Fulkerson method to compute the maximum flow in a flow
network.
Algorithm:
 Start with the source node.
 Add that node at the front of the queue to the visited list.
 Make a list of the nodes as visited that are close to that vertex.

14 | P a g e
 And dequeue the nodes once they are visited.
 Repeat the actions until the queue is empty.

Program:
def add_node(v):
if v in graph:
print(v,"Node alreay present")
else:
graph[v]=[]

def add_edge(v1,v2):
if v1 not in graph:
print(v1,"Node is not present")
elif v2 not in graph:
print(v2,"Node is not present in graph")
else:
graph[v1].append(v2)

def bfs(node,graph):
visited=set()
if node not in graph:
print(node,"Node not in graph");
return
queue=[]
queue.append(node)
while queue:
current=queue.pop(0)
if current not in visited:
print(current)
visited.add(current)
for i in graph [current]:
queue.append(i)
graph={ }
add_node("A")
add_node("B")
add_node("C")
add_node("D")
add_node("E")
add_edge("A","B")
add_edge("B","E")
add_edge("A","C")
add_edge("A","D")

15 | P a g e
add_edge("B","D")
add_edge("C","D")
add_edge("E","D")
print(graph)
print("BFS traversal of given graph is-")
bfs("A",graph)

Output:
{'A': ['B', 'C', 'D'], 'B': ['E', 'D'], 'C': ['D'], 'D': [], 'E': ['D']}
BFS traversal of given graph is-
A
B
C
D
E

FURTHER READINGS:
1. https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/
2. https://www.javatpoint.com/breadth-first-search-algorithm
3. https://www.programiz.com/dsa/graph-bfs
4. https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/tutorial/
5. https://www.simplilearn.com/tutorials/data-structure-tutorial/bfs-algorithm
6. https://www.tutorialspoint.com/data_structures_algorithms/breadth_first_traversal.htm

16 | P a g e
EXPERIMENT NO. 4

NAME OF THE EXPERIMENT: Write a program in python to implement Tic-Tac-


Toe game

LEARNING OBJECTIVE : The basic idea behind the learning system is that the system
should be able to improve its performance (P) w.r.t to a set of tasks (T) by learning from training
experience (E). The training experience (E) can be a direct (predefined set of data with individual
labels) or indirect feedback (No labels for each training example). In our case:-
 Task (T): Playing Tic-Tac-Toe
 Performance (P): Percentage of Games won against Humans
 Experience (E): Indirect feedback via solution trace (Game History) generated from
games played against itself (a clone)

PRE - REQUISITE: Fundamental AI & Python

BASIC CONCEPTS:
Theory: Tic Tac Toe is a two-player game in which the objective is to take turns and mark the
correct spaces in a 3x3 grid. Think on your feet but also be careful, as the first player who places
three of their marks in a horizontal, vertical or diagonal row wins the game.

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]))

17 | P a g e
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

18 | P a g e
print("Tic-Tac-Toe Game Designed By Jagdish Pimple")
print("Player 1 [X] --- Player 2 [O]\n")
print("see the following board before start the game-")
print(" 1 | 2 | 3 ")
print("___|___|___")
print(" 4 | 5 | 6 ")
print("___|___|___")
print(" 7 | 8 | 9 ")
print(" | | ")
print()
print("Please Wait...")
time.sleep(3)
while(Game == Running):
os.system('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()

os.system('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")

19 | P a g e
Output:

20 | P a g e
FURTHER READINGS:
1. https://towardsdatascience.com/tic-tac-toe-learner-ai-208813b5261
2. https://www.geeksforgeeks.org/finding-optimal-move-in-tic-tac-toe-using-minimax-algorithm-
in-game-theory/
3. https://realpython.com/tic-tac-toe-ai-python/
4. https://www.youtube.com/watch?v=H0hRly9JanE
5. https://www.vtupulse.com/artificial-intelligence/solve-tic-tac-toe-game-in-artificial-
intelligence/
6. https://www.pico.net/kb/what-algorithm-for-a-tic-tac-toe-game-can-i-use-to-determine-the-
best-move-for-the-ai/

21 | P a g e
EXPERIMENT NO. 5

NAME OF THE EXPERIMENT: Implement water jug problem of artificial


intelligence in python

LEARNING OBJECTIVE: To learn production rule implementation in AI problem


PRE-REQUISTICS: Basics of Production Rules

Problem Statement
Given two water jugs with capacities X and Y litres. Initially, both the jugs are empty. Also
given that there is an infinite amount of water available. The jugs do not have markings to measure
smaller quantities. One can perform the following operations on the jug:

 Fill any of the jugs completely with water.


 Pour water from one jug to the other until one of the jugs is either empty or full, (X, Y) -
> (X – d, Y + d)
 Empty any of the jugs

The task is to determine whether it is possible to measure Z litres of water using both the jugs.
And if true, print any of the possible ways.

Mathematical Approach

• Since we need to find if Z can be measured from the given jugs of X and Y litres. This
can be written in a single equation as follows:
• A*X+B*Y=Z
• where A and B are integers. Now, this is a linear Diophantine equation and is easily
solvable if. GCD(X, Y) divides Z. So, the conditions to solve this problem is:
• Z % GCD(X, Y) = 0
• X+Y>Z

Solution:

The state space for this problem can be described as the set of ordered pairs of integers (x,y)
Where,
X represents the quantity of water in the 4-gallon jug X= 0,1,2,3,4
Y represents the quantity of water in 3-gallon jug Y=0,1,2,3
Start State: (0,0)
Goal State: (2,0)

Production rules for solving the water jug problem:

22 | P a g e
S.No. Initial Condition Final state Description of action taken
State
1. (x,y) If x<4 (4,y) Fill the 4 gallon jug completely
2. (x,y) if y<3 (x,3) Fill the 3 gallon jug completely

3. (x,y) If x>0 (x-d,y) Pour some part from the 4 gallon jug
4. (x,y) If y>0 (x,y-d) Pour some part from the 3 gallon jug
5. (x,y) If x>0 (0,y) Empty the 4 gallon jug
6. (x,y) If y>0 (x,0) Empty the 3 gallon jug
7. (x,y) If (x+y)<7 (4, y-[4-x]) Pour some water from the 3 gallon jug to fill the
four gallon jug
8. (x,y) If (x+y)<7 (x-[3-y],y) Pour some water from the 4 gallon jug to fill the 3
gallon jug.
9. (x,y) If (x+y)<4 (x+y,0) Pour all water from 3 gallon jug to the 4 gallon
jug

10. (x,y) if (x+y)<3 (0, x+y) Pour all water from the 4 gallon jug to the 3
gallon jug

Example: Input: X = 3, Y = 5, Z = 4

S.No. 3 gallon jug 5 gallon jug Explanation


contents contents

1. 0 gallon 0 gallon Initial state

2. 3 gallon 0 gallons Fill the 3 gallon jug with a maximum


capacity

3. 0 gallons 3 gallon Transfer complete water from 3 gallon jug


to 5 gallon jug

4. 3 gallons 3 gallons Fill the 3 gallon jug with a maximum


capacity

5. 1 gallons 5 gallons Transfer some water from 3 gallon jug to


5 gallon jug till it becomes full

6. 1 gallon 0 gallons Empty 5 gallon jug

23 | P a g e
7. 0 gallons 1 gallon Transfer complete water from 3 gallon jug
to 5 gallon jug

8. 3 gallons 1 gallon Fill the 3 gallon jug with a maximum


capacity

9. 0 gallons 4 gallon Transfer complete water from 3 gallon jug


to 5 gallon jug
Goal Achived

Program:

class Waterjug:
def __init__(self,am,bm,a,b,g):
self.a_max = am;
self.b_max = bm;
self.a = a;
self.b = b;
self.goal = g;

def fillA(self):
self.a = self.a_max;
print ('(', self.a, ',',self.b, ')')

def fillB(self):
self.b = self.b_max;
print ('(', self.a, ',', self.b, ')')
def emptyA(self):
self.a = 0;
print ('(', self.a, ',', self.b, ')')
def emptyB(self):
self.b = 0;
print ('(', self.a, ',', self.b, ')')
def transferAtoB(self):
while (True):
self.a = self.a - 1
self.b = self.b + 1
if (self.a == 0 or self.b == self.b_max):
break
print ('(', self.a, ',', self.b, ')')

24 | P a g e
def main(self):
while (True):
if (self.a == self.goal or self.b == self.goal):
break
if (self.a == 0):
self.fillA()
elif (self.a > 0 and self.b != self.b_max):
self.transferAtoB()
elif (self.a > 0 and self.b == self.b_max):
self.emptyB()

waterjug=Waterjug(3,5,0,0,4);
waterjug.main();

Output:
(3,0)
(0,3)
(3,3)
(1,5)
(1,0)
(0,1)
(3,1)
(0,4)

FURTHER READINGS:
1. https://www.includehelp.com/ml-ai/water-jug-problem-in-artificial-intelligence.aspx
2. https://www.geeksforgeeks.org/water-jug-problem-using-bfs/
3. https://www.goeduhub.com/7743/water-jug-problem-in-artificial-intelligence
4. https://www.vtupulse.com/artificial-intelligence/water-jug-problem-in-artificial-intelligence/
5. https://favtutor.com/blogs/water-jug-problem
6. https://www.futurelearn.com/info/courses/recreational-math/0/steps/43519

25 | P a g e
EXPERIMENT NO. 6

NAME OF THE EXPERIMENT: Implementation of Missionaries & cannibals


Problem in python

OBJECTIVE: To learn the production rules implementation in AI

PRE-REQUISTICS: Basics of Production Rule

Basic Concept:

The Missionaries and Cannibals Problem (MCP) is a classic river-crossing logic puzzle.
In the missionaries and cannibals problem, three missionaries and three cannibals must cross a
river using a boat which can carry at most two people, under the constraint that, for both banks,
if there are missionaries present on the bank, they cannot be outnumbered by cannibals (if they
were, the cannibals would eat the missionaries). The boat cannot cross the river by itself with no
people on board.

To solve this problem we will make the following assumptions:

1. Number of cannibals should lesser than the missionaries on either side.

2. Only one boat is available to travel.

3. Only one or maximum of two people can go in the boat at a time.

4. All the six have to cross the river from bank.

5. There is no restriction on the number of trips that can be made to reach of the goal.

6. Both the missionaries and cannibals can row the boat.

Sr.No Left Side of River River Right Side of


River
1 MMM CCC __________

CC
2 MMM C CC

3 MMM CC C C

26 | P a g e
CC
4 MMM CCC

5 MMM C
C CC
MM
6 MC CC MM

7 MC MC MC CM
MM
8 CC CMMM

9 CCC C MMM
CC
10 C MMM CC

11 CC C MMM C
CC
12 ______Empty____ MMM CCC

#Python program
print("\n")
print("\tGame Start\nNow the task is to move all of them to right side of the river")
print("rules:\n1. The boat can carry at most two people\n2. If cannibals num greater than
missionaries then the cannibals would eat the missionaries\n3. The boat cannot cross the river by
itself with no people on board")
lM = 3 #lM = Left side Missionaries number
lC = 3 #lC = Laft side Cannibals number
rM=0 #rM = Right side Missionaries number

27 | P a g e
rC=0 #rC = Right side cannibals number
userM = 0 #userM = User input for number of missionaries for right to left side travel
userC = 0 #userC = User input for number of cannibals for right to left travel
k=0
print("\nM M M C C C | --- | \n")
try:
while(True):
while(True):
print("Left side -> right side river travel")
#uM = user input for number of missionaries for left to right travel
#uC = user input for number of cannibals for left to right travel
uM = int(input("Enter number of Missionaries travel => "))
uC = int(input("Enter number of Cannibals travel => "))

if((uM==0)and(uC==0)):
print("Empty travel not possible")
print("Re-enter : ")
elif(((uM+uC) <= 2)and((lM-uM)>=0)and((lC-uC)>=0)):
break
else:
print("Wrong input re-enter : ")
lM = (lM-uM)
lC = (lC-uC)
rM += uM
rC += uC

print("\n")
for i in range(0,lM):
print("M ",end="")
for i in range(0,lC):
print("C ",end="")
print("| --> | ",end="")

28 | P a g e
for i in range(0,rM):
print("M ",end="")
for i in range(0,rC):
print("C ",end="")
print("\n")

k +=1

if(((lC==3)and (lM == 1))or((lC==3)and(lM==2))or((lC==2)and(lM==1))or((rC==3)and


(rM == 1))or((rC==3)and(rM==2))or((rC==2)and(rM==1))):
print("Cannibals eat missionaries:\nYou lost the game")
break

if((rM+rC) == 6):
print("You won the game : \n\tCongrats")
print("Total attempt")
print(k)
break
while(True):
print("Right side -> Left side river travel")
userM = int(input("Enter number of Missionaries travel => "))
userC = int(input("Enter number of Cannibals travel => "))

if((userM==0)and(userC==0)):
print("Empty travel not possible")
print("Re-enter : ")
elif(((userM+userC) <= 2)and((rM-userM)>=0)and((rC-userC)>=0)):
break
else:
print("Wrong input re-enter : ")
lM += userM
lC += userC

29 | P a g e
rM -= userM
rC -= userC

k +=1
print("\n")
for i in range(0,lM):
print("M ",end="")
for i in range(0,lC):
print("C ",end="")
print("| <-- | ",end="")
for i in range(0,rM):
print("M ",end="")
for i in range(0,rC):
print("C ",end="")
print("\n")
if(((lC==3)and (lM == 1))or((lC==3)and(lM==2))or((lC==2)and(lM==1))or((rC==3)and
(rM == 1))or((rC==3)and(rM==2))or((rC==2)and(rM==1))):
print("Cannibals eat missionaries:\nYou lost the game")
break
except EOFError as e:
print("\nInvalid input please retry !!")

Output:
Game Start
Now the task is to move all of them to right side of the river
rules:
1. The boat can carry at most two people
2. If cannibals num greater than missionaries then the cannibals would eat the missionaries
3. The boat cannot cross the river by itself with no people on board

MMMCCC| --- |

Left side -> right side river travel


Enter number of Missionaries travel => 0

30 | P a g e
Enter number of Cannibals travel => 2

M M M C | --> | C C

Right side -> Left side river travel


Enter number of Missionaries travel => 0
Enter number of Cannibals travel => 1

M M M C C | <-- | C

Left side -> right side river travel


Enter number of Missionaries travel => 0
Enter number of Cannibals travel => 2

M M M | --> | C C C

Right side -> Left side river travel


Enter number of Missionaries travel => 0
Enter number of Cannibals travel => 1

M M M C | <-- | C C

Left side -> right side river travel


Enter number of Missionaries travel => 2
Enter number of Cannibals travel => 0

M C | --> | M M C C

Right side -> Left side river travel


Enter number of Missionaries travel => 1
Enter number of Cannibals travel => 1

M M C C | <-- | M C

Left side -> right side river travel


Enter number of Missionaries travel => 2

31 | P a g e
Enter number of Cannibals travel => 0

C C | --> | M M M C

Right side -> Left side river travel


Enter number of Missionaries travel => 0
Enter number of Cannibals travel => 1

C C C | <-- | M M M

Left side -> right side river travel


Enter number of Missionaries travel => 0
Enter number of Cannibals travel => 2

C | --> | M M M C C

Right side -> Left side river travel


Enter number of Missionaries travel => 0
Enter number of Cannibals travel => 1

C C | <-- | M M M C

Left side -> right side river travel


Enter number of Missionaries travel => 0
Enter number of Cannibals travel => 2

| --> | M M M C C C

You won the game :


Congrats
Total attempt
11

FURTHER READINGS:
1. https://www.geeksforgeeks.org/missionaries-and-cannibals/
2. https://www.aiai.ed.ac.uk/~gwickler/missionaries.html
3. https://blogs.sas.com/content/sgf/2022/02/15/missionaries-and-cannibals-problem/
4. https://sites.google.com/site/preranakakodkar09/projects/missionary-and-cannibals-problem
5. http://www-formal.stanford.edu/jmc/elaboration/node2.html
6.http://cs.oswego.edu/~kzeller/Portfolio/coursework/csc416/Visuals/Missionary_State_Space.pd
f

32 | P a g e
EXPERIMENT NO. 7

NAME OF THE EXPERIMENT: Perform the following operations using Python


(Pandas) on any open source dataset (e.g., data.csv)
1.Read CSV File (Locate open source data from the web (e.g. https://www.kaggle.com)
2. Creation of Pandas DataFrame
3. Use index_col
4.Header
5.usecols
6.skiprows
7.nrows
8.Encoding
9.Dtype
10.parse_dates
11.Convertors
12.sort_values()

OBJECTIVE: To learn the operation on CSV file using pandas library

PRE-REQUISTICS: Basics of CSV Files and Python

Basic Concept:
CSV- Comma Separated Values File-
CSV (Comma Separated Values) may be a simple file format accustomed to storing tabular data,
like a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each
line of the file could be a data record. Each record consists of 1 or more fields, separated by
commas. The use of the comma as a field separator is the source of the name for this file format.

Why Do We Use CSV Files?


CSV files are the simplest way to speak data between different applications. Say you had a
database application and wanted to export the info to a file. If you wish to export it to an Excel
file, the database application will support exporting to XLS* files.
However, since the CSV file format is extremely straightforward and lightweight (much more
than XLS* files), it’s easier for varied applications to support it. In its basic usage, you have a
line of text, with every column of data going in alternative ways by a comma. That’s it. And
since of this simplicity, it’s simple for developers to make Export / Import practicality with CSV
files to transfer knowledge between applications instead of a lot of sophisticated file formats.

Pandas DataFrame
One of the easiest ways to read a csv file in Python is using the Pandas library. It has a very
useful function, read_csv(), which allows us to read a CSV file and create a Pandas DataFrame.
A Pandas DataFrame is nothing but a two-dimensional data structure storing data like a table
with rows and columns. So here I’ll show you how to work with CSV files using Python Pandas.

33 | P a g e
Importing Pandas
Firstly, we import the necessary the Pandas Library of Python.
import pandas as pd
Now we will see how to load and read the dataset easily.
Read-csv Function
 It is an important pandas function to read CSV files and do operations on them.
 This function helps us load the file from your local machine or any URL.

Opening a Local CSV File


If the file is present in the same location as in our Python File, then give the file name only to
load that file; otherwise, you have to give the complete filepath to the file. Following is the
syntax to read a csv file and create a pandas dataframe from it.

Index-col Parameter
The index-col parameter allows us to set which columns to use as the data frame’s index.
The default value for this parameter is None, and pandas automatically will add a new column
starting from 0 to describe the index column.
So, it allows us to use a column as the row labels for a given DataFrame. This function
comes in handy quite often. Let’s say we have an ID column present with our dataset, which is
not impacting our predictions, so we make that column our index for rows instead of the default.

34 | P a g e
Header Parameter

Header parameter allows us to specify which row will be used as column names for your data

frame. It expects input as an int value or a list of int values.

The default value for this parameter is header=0, which implies that the first row of the CSV file

will be considered as column names.

Use-cols Parameter
The use-cols parameter specifies which columns to import from the complete dataset to the data
frame. It can take input from either a list of int values or directly from the column names.

35 | P a g e
This function comes in handy when we have to analyze data on just some columns and not on all
the columns of our dataset.

So, this parameter returns a subset of the columns from your dataset.

Squeeze Parameter
If true and only one column is passed, the squeeze parameter returns a pandas series instead of a
DataFrame. A Pandas series is a single-dimensional data structure storing only a single column
with a single data type.

Skiprows Parameter

Skiprows parameter is used to skip past rows in the new data frame. This is useful as we can

easily iterate through the csv data and read only the relevant rows.

36 | P a g e
Nrows Parameter

The nrows function only reads the fixed number of rows from the file. Needs an int value.This

parameter comes in handy when we have a huge dataset, and we want to load our dataset in

chunks instead of directly loading the complete dataset.

37 | P a g e
Encoding Parameter
The encoding parameter helps determine which encoding you must use for UTF when reading or
writing the files.
Sometimes, our files are not encoded in the default form, i.e., UTF-8. So, saving that with a text
editor or adding the param “encoding=’utf-8′ doesn’t work. In both cases, it returns the error.
So, to resolve this issue, we call our read_csv function with encoding=’latin1′, encoding=’iso-
8859-1′ or encoding=’cp1252′ (these are some of the various encodings found on Windows).

Dtype Parameter

The dtype parameter stands for ‘data type’ for converting data or columns. For Example, {‘a’:

np.float64, ‘b’: np.int32}

38 | P a g e
This function comes in handy when we need to convert our columns from float data type to int

data type.

Parse-dates Parameter

If we make this parameter True, then it tries to parse the index.

For Example, If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column, and if

we have to combine columns 1 and 3 and parse them as a single date column, then use [[1,3]].

39 | P a g e
Convertors Parameter

This parameter helps us to convert values in the columns based on a custom function given by

the user.

def rename(name):
if name == "Royal Challengers Bangalore":
return "RCB"

40 | P a g e
else:
return name
rename("Royal Challengers Bangalore")

Output:

‘RCB’

Pandas Dataframe.sort_values()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem
of data-centric Python packages. Pandas is one of those packages, and makes importing and
analyzing data much easier. Pandas sort_values() function sorts a data frame in Ascending or
Descending order of passed Column. It’s different than the sorted Python function since it cannot
sort a data frame and particular column cannot be selected.
Syntax:
DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’,
na_position=’last’)

Every parameter has some default values except the ‘by’ parameter.
Parameters:

by: Single/List of column names to sort Data Frame by.


axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column.
ascending: Boolean value which sorts Data frame in ascending order if True.
inplace: Boolean value. Makes the changes in passed data frame itself if True.
kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm

41 | P a g e
used to sort data frame.
na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is
‘last’.

FURTHER READINGS:
1.https://www.w3schools.com/cpp/cpp_oop.asp
2. https://www.geeksforgeeks.org/object-oriented-programming-in-cpp/
3. https://www.javatpoint.com/cpp-oops-concepts
4. https://www.programiz.com/cpp-programming/oop
5. https://www.simplilearn.com/tutorials/cpp-tutorial/oops-concepts-in-cpp
6. https://www.tutorialspoint.com/cplusplus/cpp_object_oriented.htm

EXPERIMENT NO. 8

NAME OF THE EXPERIMENT: Write a program to demonstrate the use of dynamic


memory allocation in C++

Problem Statement: Program to implement bubble sort using dynamic memory allocation

OBJECTIVE: To learn Dynamic Memory Allocation

PRE-REQUISTICS: Basics of Static Memory Allocation

FURTHER READINGS:
1. https://www.geeksforgeeks.org/working-csv-files-python/
2. https://www.analyticsvidhya.com/blog/2021/08/python-tutorial-working-with-csv-file-for-
data-science/
3. https://www.programiz.com/python-programming/csv
4. https://docs.python.org/3/library/csv.html
5. https://realpython.com/python-csv/
6. https://www.protechtraining.com/blog/post/python-for-beginners-reading-manipulating-csv-
files-737

42 | P a g e
EXPERIMENT NO. 8

NAME OF THE EXPERIMENT: Demonstrate the use of matplotlib library for


plotting the line chart, histogram on any data set.

OBJECTIVE: To learn the Metplot library

PRE-REQUISTICS: Basics of Pandas and CSV file operation.

Basic Concept:
Matplotlib-

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a


multi-platform data visualization library built on NumPy arrays and designed to work with the
broader SciPy stack. It was introduced by John Hunter in the year 2002. One of the greatest
benefits of visualization is that it allows us visual access to huge amounts of data in easily
digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram
etc. Installation : Windows, Linux and macOS distributions have matplotlib and most of its
dependencies as wheel packages

Install it using this command:

C:\Users\Admin>pip install matplotlib

Conventionally, the package is imported into the Python script by adding the following statement

from matplotlib import pyplot as plt

Where is the Matplotlib Codebase?

The source code for Matplotlib is located at this github


repository https://github.com/matplotlib/matplotlib

Line Graph Plotting-(Use Jupyter Notebook)


import matplotlib
import matplotlib.pyplot as plt
days=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
temprature=[33.45,26.3,45.6,23.5,32.5,43.6,22.4,34.3,40.5,22.1,21.3,32.5,20.4,22.1,32.9]
plt.plot(days,temprature)

43 | P a g e
plt.axis([0,15,0,45])
plt.title("Nagpur Temprature")
plt.xlabel("Days")
plt.ylabel("Tempratur")
plt.show()

Output-

Line Graph Plotting with more parameter in plot method , Grid method,
legend -
import matplotlib

import matplotlib.pyplot as plt

from matplotlib import style

days=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

temprature=[33.45,26.3,45.6,23.5,32.5,43.6,22.4,34.3,40.5,22.1,21.3,32.5,20.4,22.1,32.9]

style.use("ggplot")

plt.plot(days,temprature,"r", marker="o",linestyle="--",linewidth=3,markersize=10)

plt.axis([0,15,0,45])

plt.title("Nagpur Temprature",fontsize=15)

44 | P a g e
plt.xlabel("Days",fontsize=15)

plt.ylabel("Tempratur",fontsize=15)

plt.legend(["Temp Line"],loc=4)

plt.grid(color="k", linestyle="-",linewidth=1)

plt.show()

Output:

Line Graph Plotting with more line (Include more dataset of temperature of
other city)
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
days=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
temp_NGP=[33.45,26.3,45.6,23.5,32.5,43.6,22.4,34.3,40.5,22.1,21.3,32.5,20.4,22.1,32.9]
temp_Pune=[29.45,30.3,40.6,25.5,30.5,41.6,25.4,35.3,40.5,28.1,27.3,31.5,19.4,25.1,34.9]
style.use("ggplot")
plt.plot(days,temp_NGP,"r", marker="o",linestyle="--
",linewidth=3,markersize=10,label="NGP_Temp")

45 | P a g e
plt.plot(days,temp_Pune,"k", marker="o",linestyle="--
",linewidth=3,markersize=10,label="Pune_Temp")
plt.axis([0,15,0,45])
plt.title("Nagpur & Pune Temprature",fontsize=15)
plt.xlabel("Days",fontsize=15)
plt.ylabel("Tempratur",fontsize=15)
plt.legend(loc=4)
plt.grid(color="k", linestyle="-",linewidth=1)
plt.show()

Output:

Plotting Histograms-
import matplotlib.pyplot as plt
import numpy as np
import random
bins=[15,20,25,30,35,40,45] # specify the range
plt.figure(figsize=(16,9)) # change the histogram size
ML_student_age=np.random.randint(18,45,(100)) #generate 100 ML student from age 18 to 45
AI_student_age=np.random.randint(15,40,(100)) #generate 100 AI student from age 15 to 40

46 | P a g e
print(ML_student_age)
print(AI_student_age)
plt.hist([ML_student_age,AI_student_age],bins,rwidth=0.8,color=["red","Yellow"],label=["ML_
Student","AI_Student"])
plt.title("ML Student Age Histogram",fontsize=15)
plt.xlabel("Student age",fontsize=15)
plt.ylabel("No.of Student",fontsize=15)
plt.legend()
plt.show()

Output:

[35 32 25 24 29 39 39 19 27 39 19 39 33 38 22 30 37 39 31 18 23 31 21 32
33 25 33 24 24 32 37 26 34 18 18 41 44 19 27 43 21 24 34 24 41 44 18 22
44 19 23 43 20 38 24 27 32 34 44 19 26 34 30 18 23 27 21 44 39 28 40 21
31 44 30 21 21 29 32 39 35 33 37 19 34 33 19 38 27 23 34 31 38 40 23 23
44 35 28 42]
[16 38 35 20 25 37 28 34 25 36 32 30 16 22 37 21 39 39 21 15 31 36 38 31
23 16 28 28 15 36 26 27 17 15 37 21 23 17 32 18 16 23 17 37 21 37 21 16
16 20 21 18 32 19 33 20 21 31 26 34 31 22 38 32 37 17 26 23 39 27 39 32
21 19 29 32 30 36 36 15 31 21 35 19 37 32 27 22 33 16 32 27 20 37 38 21
31 31 25 23]

FURTHER READINGS:
1. https://www.w3schools.com/python/matplotlib_pyplot.asp
2. https://matplotlib.org/
3. https://www.geeksforgeeks.org/python-introduction-matplotlib/
4. https://www.activestate.com/resources/quick-reads/what-is-matplotlib-in-python-how-to-use-
it-for-plotting/
5. https://www.tutorialspoint.com/python_data_science/python_matplotlib.htm

47 | P a g e
48 | P a g e

You might also like