:Python关联矩阵 - 如何删除Vertex?

时间:2011-10-21 17:18:54

标签: python coding-style graph matrix

这是我的代码:

class incidenceMatrix:
    def __init__(self, vertexNumber):
        self.matrix = []
        for k in range(0, vertexNumber):
            self.matrix += [[]]
            #print self.matrix

    def showGraph(self):
        i = 1
        for row in self.matrix:
            print i, row
            i += 1

    def isEdge(self, v1, v2):
        i = 1
        for row in self.matrix:
            if i == v1:
                r1 = row
            if i == v2:
                r2 = row
            i += 1
        print r1, r2
        for x in range(len(r1)):
            if r1[x] == r2[x] and r1[x] + r2[x] > 0:
                return True
        return False

    def addEdge(self, v1, v2):
        i = 1
        for row in self.matrix:
            if i == v1:
                row.append(1)
            elif i == v2:
                row.append(1)
            else:
                row.append(0)
            i += 1

    def removeEdge(self, v1, v2):
        i = 1
        for row in self.matrix:
            if i == v1:
                r1 = row
            if i == v2:
                r2 = row
            i += 1
        for x in range(len(r1)):
            if r1[x] == r2[x] and r1[x] + r2[x] > 0:
                col = x
                r1[x] = 0
                r2[x] = 0
        for row in self.matrix:
            if i == v1:
                row = r1
            if i == v2:
                row = r2
            i += 1
        for row in self.matrix:
            row[col] = 'X'
            row.remove('X')

def removeVertex(self, id):
    pass

if __name__ == '__main__':
    GrafIM = incidenceMatrix(5) #verticesNumber
    GrafIM.addEdge(2,3)
    GrafIM.addEdge(1,3)
    GrafIM.addEdge(2,1)
    GrafIM.addEdge(5,2)
    print GrafIM.isEdge(2,4)
    GrafIM.showGraph()
    print "-------"
    GrafIM.removeEdge(2,5)
    GrafIM.showGraph()

这是关联矩阵 我有几个问题:

1)如何删除顶点 - 方法?

2)如何在python风格中创建更多代码?见问题3)

3)我要在方法中使用“i”增量吗?也许这可能是另一回事 - 但是怎么样?

编辑:

我现在看到了如何删除顶点。 我刚删除了这个顶点有1的列。

但是整个时间都在等待有关代码质量的建议

2 个答案:

答案 0 :(得分:1)

对问题2和3的回答是使用enumerate而不是递增计数器。例如,您的showGraph方法:

def showGraph(self):
    i = 1
    for row in self.matrix:
        print i, row
        i += 1

可以简化为:

def showGraph(self):
    for i, row in enumerate(self.matrix, 1):
        print i, row

答案 1 :(得分:1)

这是您要求的 removeVertex()方法。此外,使用 any() enumerate() zip()来加强代码:

class incidenceMatrix:
    def __init__(self, vertexNumber):
        self.matrix = [[] for k in range(vertexNumber)]

    def showGraph(self):
        for i, row in enumerate(self.matrix, 1):
            print i, row

    def isEdge(self, v1, v2):
        return any(x and y for x, y in zip(self.matrix[v1-1], self.matrix[v2-1]))

    def addEdge(self, v1, v2):
        for i, row in enumerate(self.matrix, 1):
            row.append(int(v1==i or v2==i))

    def removeEdge(self, v1, v2):
        num_edges = len(self.matrix[0])
        for j in range(num_edges):
            if self.matrix[v1-1][j] and self.matrix[v2-1][j]:
                for row in self.matrix:
                    del row[j]
                return
        raise Exception('Edge(%d, %d) not found' % (v1, v2))

    def removeVertex(self, v):
        targetrow = self.matrix.pop(v-1)    # fetch and delete the target vertex
        for col, selector in reversed(list(enumerate(targetrow))):
            if selector:                    # find columns that had an edge on the target row
                for row in self.matrix:
                    del row[col]            # remove that column (because the edge is gone)

if __name__ == '__main__':
    GrafIM = incidenceMatrix(5) #verticesNumber
    GrafIM.addEdge(2,3)
    GrafIM.addEdge(1,3)
    GrafIM.addEdge(2,1)
    GrafIM.addEdge(5,2)
    print GrafIM.isEdge(2,4)
    for pair in [(2,3), (1,3), (2,1), (5,2)]:
        print GrafIM.isEdge(*pair)
    GrafIM.showGraph()
    print "-------"
    GrafIM.removeEdge(2,5)
    GrafIM.showGraph()
    print "-------"
    GrafIM.removeVertex(2)
    GrafIM.showGraph()    

注意,如果放弃基于一的索引而支持Python的从零开始的索引,则可以稍微简化一下代码(从{enumerate()中删除, 1并删除-1来自索引查找。

此外,您可能希望使用 dict 考虑不同的表示形式。这更适合稀疏结构,可以稍微简化/加速代码。