条件随机矩阵

时间:2018-11-30 07:33:45

标签: python numpy matrix

我想添加以下条件:在第一行和第一列中仅获取1,在其他行和列中仅获取1。这是代码:

import numpy as np
import random


class city:
    def __init__(self):
        self.distance()

    def distance(self):
        self.A = np.array(
            [[0, 10, 20, 30], [10, 0, 25, 20], [20, 25, 0, 15], [30, 20, 15, 0]]
        )
        self.B = np.array(
            [
                [random.randint(0, 1) for j in range(self.A.shape[0])]
                for i in range(self.A.shape[1])
            ]
        )

    def route(self):
        n = (self.B.shape[0]) + 1
        nodes = list(range(n))
        route = [nodes.pop(random.sample(range(n - i), 1)[0]) for i in range(n)]
        return [(route[i], route[i + 1]) for i in range(n - 1)]


ob = city()
print(ob.route())

0 个答案:

没有答案