Home > Blockchain >  Grouping of list of tuples in python
Grouping of list of tuples in python

Time:09-11

So here i have a program which will take an input and display the input in the form of list but the thing is i want to take input separetly and to perform the grouping operation separetly because i need two variables i.e number of nodes and other is edges.Because i want to use this two variables in the below init function.

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 below code the problem is that it is doing both operation in single variable i.e t . I tried to do both separetly using this below code but not able to this .

t = list(tuple(map(int,input().split())) for r in range(int(input('enter no of rows : '))))  
print(t)

I need the output like below :

enter no of nodes : 3
enter edges :
1 2
3 4
5 6

list of edges :
[(1, 2), (3, 4), (5, 6)]

CodePudding user response:

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
  • Related