冷凝一堂课

时间:2015-03-20 00:55:15

标签: python class graph

我赶紧写了这个班级'它采用(用于初始化)图形的文本表示(作为字符串)并构造图形对象。

第一行(标题)描述了图形的类型和顶点的数量。它有两个或三个部分。第一部分是表示有向图的字符D,或表示无向图的字符U.如果图是加权的,则标题的第二部分是字符W.标题的最后部分是自然数n,表示图中的顶点数。图中的所有顶点都编号为0到n-1。

如果图表字符串有多行,则每个剩余​​行(从第二行开始)描述一条边。边的前两个部分是0和n-1之间的两个自然数,描述了用这些数字标识的两个顶点之间的边。如果图是指向的,则必须将这两个数字解释为描述从第一个顶点到第二个顶点的边的有序对。如果图是无向的,则必须将这两个数字解释为描述两个顶点之间的边的无序对。如果图表是加权的,那么第三部分将是一个整数,表示边缘的权重。

图表既可以是定向的,也可以是非定向的,加权的或非加权的

例如此图表:

graph_string = """\
D W 3
0 1 7
1 0 -2
0 2 0
"""
print(Graph(graph_string).adjacency_list) 

是指导和加权的,' 3'这些旁边的符号表示边数(在本例中为3)。

此示例的adjacency_list将输出:

[[(1, 7), (2, 0)], [(0, -2)], []]

'班级'我写过的确实能做到这一点,但不是一个班级应该采取行动的方式。我对如何把它变成一个合适的类感到困惑,我现在所知道的只是它应该只有:

class Graph:
def __init__(self, graph_string):
    self.directed  =  # true if directed, false if un-directed
    self.weighted = # true if weighted, false otherwise
    self.adjacency_list = # a list of lists

作为 init ,使用单独的方法/函数来实现其余的。

感谢您花时间阅读本文,并且随时可以提问,因为这很难说。

我的班级:

class Graph:    
def __init__(self, graph_string):
    self.graph_string = []
    graph_string = graph_string.splitlines()
    for i in graph_string:
        i = (i.split())
        self.graph_string.append(i)
    first_num = self.graph_string[0]
    d_true = first_num[0]
    sec_num = self.graph_string[0]
    w_true = sec_num[1]
    self.weighted = w_true
    self.directed = d_true
    self.graph_string.pop(0)
    if self.directed == ("D"):
        self.directed = True
    elif self.directed == ("U"):
        self.directed = False
    if self.weighted == ("W"):
        self.weighted = True
    elif self.weighted != ("W"):
        self.weighted = False
    if self.weighted == False:
        var_num = graph_string[0]
        var_num = list(var_num)
        var_num = var_num[2]
        var_num = int(var_num)
        self.adjacency_list = [[] for _ in range(var_num)]  
    elif self.weighted == True:
        var_num = graph_string[0]
        var_num = list(var_num)
        var_num = var_num[4]
        var_num = int(var_num)
        self.adjacency_list = [[] for _ in range(var_num)]             
    if self.weighted == False:
        if self.directed == True:
            for s in self.graph_string:
                num_one = s[0]
                num_one = int(num_one)
                num_two = s[1]
                num_two = int(num_two)
                self.adjacency_list[num_one].append((num_two, None))
        elif self.directed == False:
            for t in self.graph_string:
                num_one = t[0]
                num_one = int(num_one)
                num_two = t[1]
                num_two = int(num_two)
                self.adjacency_list[num_one].append((num_two, None))
                self.adjacency_list[num_two].append((num_one, None))
    elif self.weighted == True:
        if self.directed == True:
            for t in self.graph_string:
                num_one = t[0]
                num_one = int(num_one)
                num_two = t[1]
                num_two = int(num_two)
                num_three = t[2]
                num_three = int(num_three)
                self.adjacency_list[num_one].append((num_two, num_three))
        if self.directed == False:
            for t in self.graph_string:
                num_one = t[0]
                num_one = int(num_one)
                num_two = t[1]
                num_two = int(num_two)
                num_three = t[2]
                num_three = int(num_three)
                self.adjacency_list[num_one].append((num_two, num_three))
                self.adjacency_list[num_one].append((num_one, num_three))        

    (self.adjacency_list)

1 个答案:

答案 0 :(得分:1)

也许是这样的?如果您使用地图,这似乎更容易和更通用(但我将地图转换为您的情况下的列表)。

注意: 我不知道为什么字符串应该有边数,我没有使用它。另外,请注意我没有进行任何检查以查看字符串格式是否正确。

class Graph:
    def __init__(self, graph_string):
        elements = graph_string.split()
        self.directed = elements[0] == 'D'
        self.weighted = elements[1] == 'W'
        self.adjacency_list = []

        elements = elements[3:]

        graph_map = {}
        entries_per_line = 3 if self.weighted else 2
        elements = [elements[i:][:entries_per_line] for i in range(0,len(elements),entries_per_line)]
        for t in elements:
            lhs = int(t[0])
            rhs = int(t[1])
            if lhs not in graph_map:
                graph_map[lhs] = []
            if rhs not in graph_map:
                graph_map[rhs] = []
            val = (rhs, float(t[2])) if self.weighted else rhs
            graph_map[lhs].append(val) 
        for k in sorted(graph_map.keys()):
            self.adjacency_list.append(graph_map[k])


gs = """\
D W 3
0 1 7
1 0 -2
0 2 0
"""

print Graph(gs).adjacency_list
#[[(1, 7.0), (2, 0.0)], [(0, -2.0)], []]
相关问题