簡體   English   中英

從矩陣創建隨機數組

[英]Creating a random array from a matrix

我有以下代碼用於從矩陣返回數組,但是它不起作用。 我想知道您是否可以幫助我進行更正。 謝謝你

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

您可以選擇任意的節點旁參觀,並從節點中刪除所選擇的節點是訪問列表( 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)]

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 = [[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()打印(ob.route())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM