Python Learning Week 4 (Solution)

Tasks

Implement the given Graph in Python.

  1.  Write a method to output degree of each node within the graph.
  2. Write a method to find any path from node 6 to node 1 in given Graph.
  3.  Modify part 2 to show all possible paths between node 6 to node 1 in Graph.
image 6 - Python Learning Week 4 (Solution)

CODE:

for a in graph:

        degree=0

        for g in graph[a]:

            if g==a:

                degree=degree+2

            else:

                degree=degree+1

        print(“degree of vertex”,a,” is\n “,degree)

def path(Start=1,end=6,checklist=[]):

    if Start not in checklist:

        checklist.append(Start)

        if Start!=end:

            print(Start)

            List=graph[Start]

            for a in List:

                if a in checklist:

                    List.remove(a)

            for a in List:

                if end not in List:

                    path(a)

                    break

                else:

                    print(end)

                    break

        print(checklist)

graph = {

        6 : [4],

        4 : [5,4,6],

        3 : [2,4],

        5 : [4,2,1],

        2 : [5,1],

        1 : [5,2]}

degree()

path()

OUTPUT:

image 7 - Python Learning Week 4 (Solution)

What we Studied in Week 4:

In this week 4, we study graphs basically graph which is non-linear data structure consisting of edges and nodes. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. Graphs are used to solve real-life problems that involve representation of the problem space as a network. Also implement graph in python this all we study in this week.