从矩阵创建随机数组

2024-04-19 00:19:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下从矩阵返回数组的代码,但它不起作用。我想知道你能不能帮我改正一下。多谢了。你知道吗

import numpy as np

class city:
    def  __init__(self,A,route):
        self.A=A
        self.route=route

    def  distance(self):
        A = np.array([[ 0,  10,    20,  30],[10,   0,    25,  20],[20,  25,     0,  15],[30,  20,    15,   0]])
        return A

    def route(self,A):
        route = random.sample(A, len(A[:,0]))
        return route

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

预期产量:

[(0,1),(1,2),(2,3)]

Tags: 代码importselfnumpycityreturninitdef
2条回答

将numpy作为np导入 随机导入 班级城市: def初始化(自身): 自我距离()

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 = [[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]
    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=城市() 打印(ob.路线())

您可以选择下一个要访问的随机节点,并从要访问的节点列表中删除所选节点(nodes)。你知道吗

最后根据当前和下一个节点对的值创建单元地址。你知道吗

它确保每个节点只拾取一次(每行和每列各拾取一个节点),并且不会返回到同一个节点(a_ii

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]
        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())

输出:

[(1, 0), (0, 3), (3, 2)]

相关问题 更多 >