Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 51

Amity School of Engineering and Technology

MODULE 1

Graph in python

Programme: B. Tech-IT,
Semester: VIth
Course: Artificial Intelligence (CSE401)
Name of Faculty: Dr. Deepti Mehrotra
1
Learning objective
• Implement graph in python

2
Graph
• Graphs are collections of
nodes and connections.
• AI problems can be modelled
and solved by graphs.
• In Graph lexicon, a node and
a connection are known
as Vertex and Edge,
respectively.
• Circles are vertices and lines
are the edges.
3
Graph types
• By defining rules for vertices and edges, we
can create different types of graph.
– if there is direction for edges, it is Directed
Graphs.
– if there is a rule that graphs can not have a cycle, it
is Acyclic Graphs.
– Combining the two, is Directed Acyclic Graphs
(DAGs).
– If weight to edges then it is Weighted Graphs.

4
Graph representation in memory:
• There are two common memory
representations of a graph.
• One is Adjacency Matrix,
• Other is Adjacency List.
• Adjacency in this context means direct
connection.

5
Adjacency Matrix
• This is the easiest way to represent a graph in
the memory. But it takes a lot of space. If you
have V vertices, it takes O(V²) space, which
only gets efficient if you get closer to a fully
connected graph. In real applications, most
matrices are sparse (i.e. empty) and this
implementation is not space efficient.

6
7
8
Adjacency List:
• This is the space-efficient alternative of the
adjacency matrix. It is also the preferred way
of representing medium to large graphs.
• As you can see in the below figure, in
adjacency list, we create a master list of all
vertices in the graph object, and each item in
the graph object is connected to a vertex object
that contains adjacent vertices and the weight
of edge
9
10
# General Graph implementation w/ Adjacency List

# Vertex object
class Vertex(object):

def __init__(self,key):
self.id = key
self.connectedTo = {}

def addNeighbor(self,neighbor,weight=0):

self.connectedTo[neighbor] = weight

def getConnections(self):
return self.connectedTo.keys()

def getId(self):
return self.id

def getWeight(self, neighbor):


return self.connectedTo[neighbor]

def __str__(self):
return str(self.id)

11
# Graph object
class Graph(object):

def __init__(self):
self.masterList = {}
self.totalNum = 0

def addVertex(self, key):


self.totalNum += 1
newVertex = Vertex(key)
self.masterList[key] = newVertex
return newVertex

def getVertex(self,n):
if n in self.masterList:
return self.masterList[n]
else:
return None

12
def addEdge(self, fromV, toV,
weight=0):
if fromV not in self.masterList:
self.addVertex(fromV)
if toV not in self.masterList:
self.addVertex(toV)

self.masterList[fromV].addNeighbor(sel
f.addVertex(toV), weight)

def getVertices(self):
return self.masterList.keys()

def __iter__(self):
# this sepcial function allows us to
iterate through master list
return iter(self.masterList.values())

def __contains__(self,n):
# this special function allows us to use
IN operator
if n in self.masterList:
return True
else:
return False

13
if __name__ == '__main__':
g = Graph()
for i in range(6):
g.addVertex(i)

g.addEdge(0,1,5)
# iteration through the master list
for vert in g:
print(vert)

14
• implement graph in python using dictionary
data structure in python.
• The keys of the dictionary used are the nodes
of graph and the corresponding values are lists
with each nodes, which are connecting by an
edge.
This simple graph has six nodes (a-f) and five
arcs:

15
a -> c
b -> c
b -> e
c -> a
c -> b
c -> d
c -> e
d -> c
e -> c
e -> b

16
• It can be represented by the following Python
data structure.
• This is a dictionary whose keys are the nodes
of the graph.
• For each key, the corresponding value is a list
containing the nodes that are connected by a
direct arc from this node.

17
• graph = { "a" : ["c"],
• "b" : ["c", "e"],
• "c" : ["a", "b", "d", "e"],
• "d" : ["c"],
• "e" : ["c", "b"],
• "f" : []
• }

18
# import dictionary for graph
from collections import defaultdict

# function for adding edge to graph


graph = defaultdict(list)
def addEdge(graph,u,v):
graph[u].append(v)

# definition of function
def generate_edges(graph):
edges = []

19
# for each node in graph
for node in graph:

# for each neighbour node of a single node


for neighbour in graph[node]:

# if edge exists then append


edges.append((node, neighbour))
return edges

20
Problem solving

21
Problem representation

22
Solving Problems
• Define the problem
• Analyse the problem
• Isolate and represent the task knowledge
to solve the problem
• Choose the best problem solving
techniques and apply them to solve the
particular problem..

23
States

24
State modification:
successor function

25
State space

26
Problem solution

27
Problem description

28
Well Defined Problems and
Solutions

0 29
3
/
Example: Water Pouring

0 30
3
/
A Water Jug Problem
Puzzle-Solving as Search
Example: Water Pouring

0 33
3
/
Example: Water Pouring

0 34
3
/
Production Rules for the Water
Jug Problem
Fill the 4-gallon jug
1 (x,y)  (4,y)
if x < 4 Fill the 3-gallon jug
2 (x,y)  (x,3)
if y < 3 Pour some water out of the 4-gallon jug
3 (x,y)  (x – d,y) Pour some water out of the 3-gallon jug
if x > 0 Empty the 4-gallon jug on the ground
4 (x,y)  (x,y – d)
if x > 0 Empty the 3-gallon jug on the ground
5 (x,y)  (0,y) Pour water from the 3-gallon jug into
if x > 0 the 4-gallon jug until the 4-gallon jug
6 (x,y)  (x,0) is full
if y > 0
7 (x,y)  (4,y – (4 – x))
if x + y ≥ 4 and y > 0
The Water Jug Problem (cont’d)

8 (x,y)  (x – (3 – y),3) Pour water from the 4-gallon jug


if x + y ≥ 3 and x > 0 into the 3-gallon jug until the
3-gallon jug is full
9 (x,y)  (x + y, 0) Pour all the water from the 3-
gallon jug into the 4-gallon jug
if x + y ≤ 4 and y > 0
Pour all the water from the 4-
10 (x,y)  (0, x + y) gallon jug into the 3-gallon jug
if x + y ≤ 3 and x > 0
Pour the 2 gallons from the 3-
11 (0,2)  (2,0) gallon jug into the 4-gallon jug

12 (x,2)  (0,2) Empty the 4-gallon jug on the


ground
One Solution to the Water Jug
Problem
Gallons in the Gallons in Rule
4-Gallon Jug the 3-Gallon Applied
Jug
0 0 2
0 3 9
3 0 2
3 3 7
4 2 5 or 12
0 2 9 or 11
2 0
Example: Water Pouring
(0,0)

(4,0) (0,3)

(1,3) (4,3) (3,0)

(1,0) (0,1)
(3,3) (4,2)

(4,1)
(2,3)

(2,0) (0,2)

0 38
3
/
• Given:
• a five gallon jug
• a seven gallon jug
• a way to fill up the jugs
• a way to pour out water
• End up with:
• exactly 1 gallon of water in one of the jugs.

39
water space water space
start with both
0 5 0 7
jugs empty
fill the 7 0 5 7 0
pour 7 into 5 5 0 2 5
empty the 5 0 5 2 5
pour 7 into 5 2 3 0 7
fill the 7 2 3 7 0
pour 7 into 5 5 0 4 3
empty the 5 0 5 4 3
pour 7 into 5 4 1 0 7
fill the 7 4 1 7 0
pour 7 into 5 5 0 6 1
empty the 5 0 5 6 1
pour 7 into 5
5 0 1 6
(done)
empty the 5
(just to be 0 5 1 6 40
tidy)
• We've filled the 7 gallon jug three times, and
emptied the 5 gallon jug four times.
• Each time we filled the 7 gallon jug, it started
out empty.
• Each time we emptied the 5 gallon jug, we
emptied it at a time that it was full.
• That can be expressed as:
• (7⋅3) + (5⋅(-4)) = 21 - 20 = 1

41
• at various times there was 2, 4 and 6 in the
seven gallon jug.
• How can we make 3?
• That is, can we find integers a and b such
that 7a + 5b = 3?
• If we solve the equation for b, we get:
• b = (3 -7a)/5
• Since m and n both have to be integers, we can
just try some different integers for a until we
42
get a result for b that is also an integer.
• That is, we need (3-7a) to be divisible by 5:
• So, if b is -5, and a is 4, then we have our answer: 7(4) + 5(-5)
=3
• So, this would suggest that if we just continue the process we
used to get 1 gallon just one more step, we can get three
gallons:
a 3-7a
0 3-0=3
1 3-7=-4
2 3-14=-11
3 3-21=-18
4 3-28=-25
43
• So we repeat the last two lines of the table above:
water space water space
start with both
0 5 0 7
jugs empty

many steps omitted here (see table above)
here next are the last two lines of the previous table:

pour 7 into 5
5 0 1 6

empty the 5
0 5 1 6

and we continue from here:


pour 7 into 5 1 4 0 7
fill the 7 1 4 7 0
pour 7 into 5
5 0 3 7
(done)
empty the 5
0 5 3 7
(just to be tidy) 44
• Now, the real reason for emptying the five at
the end should become more clear—it makes
the math work out. We can use the
equation ap + bq = x, where:
• p and q are the sizes of the jugs
• x is the amount of water we are looking for
• a and b represent how many times we fill up or
empty the jugs

45
Example: Eight Puzzle
• States:
– Description of the eight
tiles and location of the 7 2 4
blank tile
• Successor Function: 5 6
– Generates the legal states 8 3 1
from trying the four actions
{Left, Right, Up, Down}
• Goal Test:
– Checks whether the state
matches the goal 1 2 3
configuration
• Path Cost: 4 5 6
– Each step costs 1
7 8

03/18/2024 46
Example: Eight Puzzle

0 47
3
/
Example: Eight Queens
• Place eight queens on a Q
chess board such that no
queen can attack another Q
queen
Q
• No path cost because Q
only the final state
counts! Q
Q
• Incremental formulations
• Complete state Q
formulations Q
03/18/2024 48
Example: Eight Queens
• States:
– Any arrangement of 0 to 8
Q
queens on the board
• Initial state:
Q
– No queens on the board Q
• Successor function:
– Add a queen to an empty Q
square
• Goal Test: Q
– 8 queens on the board and
none are attacked Q
• 64*63*…*57 = 1.8*1014
possible sequences Q
– Ouch!
Q
03/18/2024 49
Example: Eight Queens
• States: Q
– Arrangements of n queens,
one per column in the Q
leftmost n columns, with no
queen attacking another Q
are states
• Successor function: Q
– Add a queen to any square
in the leftmost empty Q
column such that it is not
attacked by any other Q
queen.
• 2057 sequences to Q
investigate Q
03/18/2024 50
Amity School of Engineering and Technology

Thank You

51

You might also like