Professional Documents
Culture Documents
AI ML Manual for 22-23
AI ML Manual for 22-23
PRACTICAL HANDBOOK
EXPERIMENT NO. 1
1|Page
NAME OF THE EXPERIMENT: To Study of artificial Intelligence
BASIC CONCEPTS:
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."
"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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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:
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
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
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
LEARNING OBJECTIVE : To learn the concept DFS graph traversing using python
BASIC CONCEPTS :
Theory:
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
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)
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'
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(" | | ")
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
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:
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)
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
23 | P a g e
7. 0 gallons 1 gallon Transfer complete water from 3 gallon jug
to 5 gallon jug
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
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.
5. There is no restriction on the number of trips that can be made to reach of the goal.
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((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| --- |
30 | P a g e
Enter number of Cannibals travel => 2
M M M C | --> | C C
M M M C C | <-- | C
M M M | --> | C C C
M M M C | <-- | C C
M C | --> | M M C C
M M C C | <-- | M C
31 | P a g e
Enter number of Cannibals travel => 0
C C | --> | M M M C
C C C | <-- | M M M
C | --> | M M M C C
C C | <-- | M M M C
| --> | M M M C C C
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
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.
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.
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
The default value for this parameter is header=0, which implies that the first row of the CSV file
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
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’:
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
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:
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
Problem Statement: Program to implement bubble sort using dynamic 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
Basic Concept:
Matplotlib-
Conventionally, the package is imported into the Python script by adding the following statement
–
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
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