Here's the improved version of your question for Stack Overflow:
I have a program that takes input and displays it in the form of a list. However, I want to take input separately and perform the grouping operation separately because I need two variables: the number of nodes and the edges. I need these two variables for the __init__
function of the Graph
class.
Here's the Graph
class:
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)
# Example usage:
# g1 = Graph(num_nodes, edges)
# print(g1)
In the code below, the problem is that it performs both operations in a single variable t
. I want to separate these operations:
t = list(tuple(map(int, input().split())) for _ in range(int(input('enter number of rows: '))))
print(t)
I need the output to look like this:
enter number of nodes: 3
enter edges:
1 2
3 4
5 6
list of edges:
[(1, 2), (3, 4), (5, 6)]
How can I modify my code to take the number of nodes and edges as separate inputs and store them in separate variables? Here's what I have tried so far:
num_nodes = int(input('enter number of nodes: '))
edges = []
num_edges = int(input('enter number of edges: '))
print('enter edges:')
for _ in range(num_edges):
edge = tuple(map(int, input().split()))
edges.append(edge)
print('list of edges:')
print(edges)
When I use this input method, how can I correctly initialize and use the Graph
class with these variables? Any suggestions or improvements are welcome!
If I'm following your question correctly, and all you want is getting back the "enter no of nodes:" input value, then just call len(t)
like this:
t = list(tuple(map(int, input("enter edges: ").split())) for r in range(int(input("enter no of nodes: "))))
print("list of edges: ", end="")
print(t)
print("num_nodes: ", end="")
print(len(t))
With your example values this prints:
enter no of nodes: 3
enter edges: 1 2
enter edges: 3 4
enter edges: 5 6
list of edges: [(1, 2), (3, 4), (5, 6)]
num_nodes: 3