简体   繁体   English

创建关联矩阵

[英]Creating incidence Matrix

I'm new to stackoverflow. 我是stackoverflow的新手。 I've searched for a topic that fits my problem but unfortunately I didn't find one. 我搜索了一个适合我的问题的主题,但不幸的是我找不到一个。 So I'm opening a new topic. 所以我正在开一个新话题。

I have to implement a function in python which creates a incidence matrix out of a certain input. 我必须在python中实现一个函数,它从某个输入中创建一个关联矩阵。 My problem is that I didn't quite understand how to access the indeces and so each column only has just one '1' in it instead of two ..:/ 我的问题是我不太明白如何访问indeces,所以每列只有一个'1'而不是两个..:/

Hope you guys can help me..kinda loosing my mind on this one 希望你们能帮助我......让我在这个问题上失去理智

class incidence_matrix:
    def __init__(self, vertices, edges):
        self.vertices = vertices
        self.edges = edges
        self.liste = [[0 for i in range(vertices)] for i in range(vertices)]
        #print(self.liste)
        for i in range(0, vertices):
            for j in range(0, len(edges)):
                if edges[i][j-1] >= vertices or edges[i][j-1] < 0 or edges[i][j-1] >= vertices or edges[i][j-1] < 0:
                    print("Index out of range")
                    return
                self.liste[edges[0][j+1]][edges[1][j+1]] = 1
                self.liste[edges[1][j+1]][edges[0][j+1]] = 1

        for x in range(0, vertices):
            row = ""
            for y in range(0, len(edges)):
                row = row + str(self.liste[x][y]) + " "
            print(row)

This should work for you. 这应该适合你。 It makes the assumption that edges are bidirectional. 它假设边是双向的。

class incidence_matrix:
    def __init__(self, vertices, edges):
        self.vertices = vertices
        self.edges = edges
        self.liste = [[0 for i in range(vertices)] for i in range(len(edges))]
        for i in range(len(edges)):
            v1, v2 = edges[i]
            if v1 >= vertices:
                continue
            if v2 >= vertices:
                continue
            self.liste[i][v1] = 1
            self.liste[i][v2] = 1

        for i in range(len(edges)):
            row = ' '.join([str(x) for x in self.liste[i]])
            print(row)

Input: 输入:

graph = incidence_matrix(4, [(1,2),(0,1),(0,2)])

Output: 输出:

0 1 1 0
1 1 0 0
1 0 1 0

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

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