I am not able to get that what's wrong with the below code it should show me the output as
0 : [1, 4]
1 : [0, 2, 4, 3]
2 : [1, 3]
3 : [2, 4, 1]
4 : [3, 0, 1]
But it showing error as below :
Traceback (most recent call last):
File "C:\Users\sanja\PycharmProjects\DSA\pythonProject\main.py", line 19, in <module>
g1 = Graph(num_nodes,edges)
File "C:\Users\sanja\PycharmProjects\DSA\pythonProject\main.py", line 10, in __init__
self.data[v1].append(v2)
IndexError: list index out of range
And the program look like below :
edges = list(tuple(map(int, input("enter edges: ").split())) for r in range(int(input("enter no of nodes: "))))
num_nodes =len(edges)
class Graph:
def __init__(self, num_nodes, edges):
self.data = [[] for _ in range(num_nodes)]
for v1, v2 in edges:
self.data[v1].append(v2)
self.data[v2].append(v1)
def __repr__(self):
return "\n".join(["{} : {}".format(i, neighbors) for (i, neighbors) in enumerate(self.data)])
def __str__(self):
return repr(self)
g1 = Graph(num_nodes,edges)
print(g1)
Here in the above program i am taking num of nodes as well as edges an showing the proper format as shown above in the 1st section but getting error.
The program below is doing same work that i need to do the only thing is i need to implement with user input means at run time the inputs to be given .
num_nodes1 = 5
edges1 = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (1, 4), (1, 3)]
num_nodes1, len(edges1)
class Graph:
def __init__(self, num_nodes, edges):
self.data = [[] for _ in range(num_nodes)]
for v1, v2 in edges:
self.data[v1].append(v2)
self.data[v2].append(v1)
def __repr__(self):
return "\n".join(["{} : {}".format(i, neighbors) for (i, neighbors) in enumerate(self.data)])
def __str__(self):
return repr(self)
g1 = Graph(num_nodes1, edges1)
print(g1)
Issues: There are a couple of issues in the code.
self.datafor each node. You will need to remove duplicates.Solution: Please find the code for the
__init__function with the corrections below.You would invoke the above function as follows:
Output: Running the above with your sample data will produce the following when you run
print(self.data):