如何在python中生成随机树?

时间:2019-02-25 22:29:56

标签: python random graph tabu-search

我想在Python中实现禁忌搜索,以解决与图有关的问题(查找树,着色问题以及诸如此类的东西)。我已经用Python编写了基本代码,这是我第一次编写类似的代码。我知道该算法的工作原理(理论上),并且在实现它时遇到了一些麻烦。

生成随机解的最佳方法是什么,这样我就可以启动算法了?我想从初始图生成随机树:

graph = { "a" : ["c"],
      "b" : ["c", "e"],
      "c" : ["a", "b", "d", "e"],
      "d" : ["c"],
      "e" : ["c", "b"],
      "f" : []
    }

我正在使用以下功能来查看边缘和孤立的节点:

def generate_edges(graph):
    edges = []
    for node in graph:
        for neighbour in graph[node]:
            edges.append((node, neighbour))

    return edges

print(generate_edges(graph))


def find_isolated_nodes(graph):
    """ returns a list of isolated nodes. """
    isolated = []
    for node in graph:
        if not graph[node]:
            isolated += node
    return isolated

print(find_isolated_nodes(graph))

然后找到路径:

def find_all_paths(self, start_vertex, end_vertex, path=[]):
""" find all paths from start_vertex to
    end_vertex in graph """
graph = self.__graph_dict
path = path + [start_vertex]
if start_vertex == end_vertex:
    return [path]
if start_vertex not in graph:
    return []
paths = []
for vertex in graph[start_vertex]:
    if vertex not in path:
        extended_paths = self.find_all_paths(vertex,
                                             end_vertex,
                                             path)
        for p in extended_paths:
            paths.append(p)
return paths

我需要找到一棵树作为随机解决方案,以便我可以对其进行更改,直到它成为图中最大的树为止。

最好的方法是什么?谢谢。

0 个答案:

没有答案