0

I have the following txt file:

31  1262    -1
531 13930   1
531 16139   -1
531 17567   1
531 20653   1

The first column show the starting nodes and the second column shows the ending nodes. I want to create a graph like

graph = {'0': set(['1', '2']),
         '1': set(['0', '3', '4']),
         '2': set(['0']),
         '3': set(['1']),
         '4': set(['2', '3'])}

using the input from text file. I saved the first column in start_vertex = [] and the second column in end_vertex = []. I wrote the code below but i cant save the graph.

for i in range(len(lines)):
    v = start_vertex[i]
    if v == start_vertex[i]:
        graph = graph + {'v' : set(['end_vertex[i]'])}

And the full code is here:

file = open("network.txt","r")
lines = file.readlines()
start_vertex = []
end_vertex = []
sign = []
graph = []

for x in lines:
    start_vertex.append(x.split('\t')[0])
    end_vertex.append(x.split('\t')[1])
    sign.append(x.split('\t')[2])
file.close()


def dfs(graph, start, visited = None):
    if visited is None:
        visited = set()
        visited.add(start)
        print(start)
        for next in graph[start] - visited:
            dfs(graph, next, visited)
        return visited

for i in range(len(lines)):
    v = start_vertex[i]
    if v == start_vertex[i]:
        graph = graph + {'v' : set(['end_vertex[i]'])}
1
  • If you are working with graphs, try the awesome NetworkX package. Commented Nov 11, 2017 at 19:49

1 Answer 1

1

From your question, it is not clear what is your exact input and what is the expected output. You didn't mention what the third column means in the input text file. Besides, your program has severe problems.

I am guessing you are trying to store the input graph as follows.

lines = [(31, 1262, -1), (531, 13930, 1), (531, 16139, -1), (531, 17567, 1), (531, 20653, 1)]
start_vertex, end_vertex = [], []
for line in lines:
    start_vertex.append(line[0])
    end_vertex.append(line[1])

graph = {}
for i in range(len(lines)):
    v = start_vertex[i]
    if v in graph:
        graph[v] |= set([end_vertex[i]])
    else:
        graph[v] = set([end_vertex[i]])

print(graph)

Output:

{531: {13930, 16139, 20653, 17567}, 31: {1262}}

which is in the form: {start_v1: {end_v4, end_v5, ...}, start_v2: {end_v3}}.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.