简体   繁体   中英

Creating a random array from a matrix

I have the following code for returning an array from a matrix, but it does not work. I was wondering if you could help me correct it. Thanks a bunch.

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)                        

Expected output:

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

You can choose the random nodes to visit next and remove the chosen node from the nodes to be visited list ( nodes ).

Finally create the cell address based on the current and next node pair values.

It makes sure each node is picked only once (one in each row and each column) and also not going back to the same node ( 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())

output:

[(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() print(ob.route())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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