gpt4 book ai didi

python - 从矩阵创建随机数组

转载 作者:太空宇宙 更新时间:2023-11-03 21:31:07 25 4
gpt4 key购买 nike

我有以下代码用于从矩阵返回数组,但它不起作用。我想知道你是否可以帮我改正它。非常感谢。

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

最佳答案

将 numpy 导入为 np随机导入类(class)城市: def init(自身): 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 = [[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.route())

关于python - 从矩阵创建随机数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53513310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com