简体   繁体   English

在有向图中检测循环 Python

[英]Detecting a Cycle in a Directed Graph Python

I am trying to extract a directed graph from a text file that looks like this (1: is node, second number is neighbor, followed by weight, neighbor, weight, etc:我正在尝试从看起来像这样的文本文件中提取有向图(1:是节点,第二个数字是邻居,然后是权重、邻居、权重等:

1: 2 3 4 5 6 2
2: 3 -4
3: 8 4
4: 5 6
5: 4 -3 8 8
6: 7 3
7: 6 -6 8 7
8:

Below is my code:下面是我的代码:

fileName = ("graphin_Fig1.txt")
dictionary = {}     # allocate dictionary space
with open(fileName,'r') as file:    # open file
    for line in file:   # read each line of the file
        tokens = line.strip().split(' ')    # separate each number, remove white space
        node = int (tokens[0].split(':')[0])    # remove :, separate node from neighbors and weights
        pos = 1 # initialize counter        
        listtups = []   # allocate array to hold neghbors and weights
        while pos < len(tokens):  # while end of line has not been reached              
            listtups.append((int(tokens[pos]), int (tokens[pos++1])))   # add ints to array
            pos += 2    # counter
        if len(listtups) > 0:   # if neigbors and edges are detected
            dictionary[node] = listtups    # add to nodes
print (dictionary)
  

This is the output:这是 output:

 `{1: [(2, 3), (4, 5), (6, 2)], 2: [(3, -4)], 3: [(8, 4)], 4: [(5, 6)], 5: [(4, -3), (8, 8)], 6: [(7, 3)], 7: [(6, -6), (8, 7)]}`

I am trying to use my dictionary for other algorithms, but they will only work if the dictionary looks like the example below:我正在尝试将我的字典用于其他算法,但只有当字典看起来像下面的示例时它们才会起作用:

dictionary = {
    1: {2: 3, 4: 5, 6: 2},
    2: {3: -4},
    3: {8: 4},
    4: {5: 6},
    5: {4: -3, 8: 8},
    6: {7: 3},
    7: {6: -6, 8: 7},
    8: {}
}

I am new to python and really struggling.我是 python 的新手,真的很挣扎。 How do I change my code to make my extracted dictionary look like the example directly above?如何更改我的代码以使我提取的字典看起来像上面的示例?

You are very close.你很亲密。 The only thing left is to convert your list of tuples to dictionary, so instead of:剩下的唯一事情就是将您的元组列表转换为字典,而不是:

dictionary[node] = listtups    # add to nodes

try尝试

dictionary[node] = dict(listtups)

And remove if statement that checks for length of neigthbours, as your example shows that you want to add node even when there is no adjacent nodes.并删除检查邻居长度的if语句,因为您的示例显示即使没有相邻节点,您也希望添加节点。

Well, you don't have the same datastructure at all.好吧,您根本没有相同的数据结构。 What you want is a dictionnary that contains dictionaries.你想要的是一个包含字典的字典。 Eg:例如:

outer_d = {"inner_d":{...}, ...}

What you're doing is a dictionnary, whose values for each key isn't a dictionnary but a list (of tuples), eg:你正在做的是一个字典,每个键的值不是字典,而是一个列表(元组),例如:

outer_d = {"key":[...], ... }

Do you understand the difference?你明白其中的区别吗?

fileName = ("graphin_Fig1.txt")
dictionary = {}     
with open(fileName,'r') as file:    
    for line in file:  
        tokens = line.strip().split(' ')
        node = int (tokens[0].split(':')[0]) 
        pos = 1 # initialize counter        
        listtups = {}   # another dictionnary, not a list!
        while pos < len(tokens): 
            listtups[int(tokens[pos])] =  int(tokens[pos++1]) 
            pos += 2    # counter
        if len(listtups) > 0:
            dictionary[node] = listtups 
print (dictionary)

Which yields:产生:

{1: {2: 3, 4: 5, 6: 2}, 2: {3: -4}, 3: {8: 4}, 4: {5: 6}, 5: {4: -3, 8: 8}, 6: {7: 3}, 7: {6: -6, 8: 7}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM