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)
CodePudding user response:
Issues: There are a couple of issues in the code.
- The edges specified can be more than the number of nodes so you will need to know how many edges to read in (e.g. 7 edges for 5 nodes)
- You need unique edges in
self.data
for each node. You will need to remove duplicates.
Solution: Please find the code for the __init__
function with the corrections below.
def __init__(self, num_nodes, edges):
self.data = [[] for _ in range(num_nodes)]
# link nodes
for v1, v2 in edges:
for edge in edges:
self.data[v1].append(v2)
self.data[v2].append(v1)
# remove duplicates
self.data = [list(set(entry)) for entry in self.data]
You would invoke the above function as follows:
num_nodes = int(input("enter no of nodes: "))
num_edges = int(input("how many edges?: "))
edges = [tuple(map(int, input("enter edge: ").split())) for r in range(num_edges)]
g1 = Graph(num_nodes, edges)
print(g1)
Output: Running the above with your sample data will produce the following when you run print(self.data)
:
0 : [1, 4]
1 : [0, 2, 3, 4]
2 : [1, 3]
3 : [1, 2, 4]
4 : [0, 1, 3]