繁体   English   中英

在有向图中检测循环 Python

[英]Detecting a Cycle in a Directed Graph Python

我正在尝试从看起来像这样的文本文件中提取有向图(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:

下面是我的代码:

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)
  

这是 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)]}`

我正在尝试将我的字典用于其他算法,但只有当字典看起来像下面的示例时它们才会起作用:

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: {}
}

我是 python 的新手,真的很挣扎。 如何更改我的代码以使我提取的字典看起来像上面的示例?

你很亲密。 剩下的唯一事情就是将您的元组列表转换为字典,而不是:

dictionary[node] = listtups    # add to nodes

尝试

dictionary[node] = dict(listtups)

并删除检查邻居长度的if语句,因为您的示例显示即使没有相邻节点,您也希望添加节点。

好吧,您根本没有相同的数据结构。 你想要的是一个包含字典的字典。 例如:

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

你正在做的是一个字典,每个键的值不是字典,而是一个列表(元组),例如:

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

你明白其中的区别吗?

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)

产生:

{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