jeudi 15 septembre 2022

Randomly generating different list from list

first I created a list called “citys” then it tried to swap randomly two elements in the “citys” list for 5 times and at the same time tried to store the new lists in the “number_of_citys” but it turns out bad every time it loops, it insert the last swapped arrays only. I used this randomly generated list , citys= [[1,2], [3,4],[1,3],[5,2]] , to create another list. And I expected my list to be, orders_of_citys=[[[1,2], [5,2],[1,3][3,4]] , [[5,2], [1,2],[1,3][3,4]],[ [1,3], [1,2],[5,2][3,4]], [[3,4], [1,2],[5,2][1,3]], [1,3], [1,2],[5,2][3,4]] ] but I got the following order_of_citys =[[[1,3], [1,2],[5,2][3,4]], [1,3], [1,2],[5,2][3,4]], [1,3], [1,2],[5,2][3,4]] ,[1,3], [1,2],[5,2][3,4]], [1,3], [1,2],[5,2][3,4]]] I have used append(), +=, and insert built in function and operators but I still get the same array. please I would like some one to point me my problem.The code I wrote is the following.

import random
  
citys = []
number_of_cities = 5
orders_of_citys = []
pop = 5

#give random place for cities on 2D plane
for i in range(number_of_cities):
        citys.append( [ random.randint(0, 1000), random.randint(0, 1000)])

#suffle  points (citys) position to get different path
def swap(c, a, b):
        value = c[a]
        c[a] = c[b]
        c[b] = value
        return c

for j in range(pop):
    a = random.randint(0, len(citys)-1)
    b= random.randint(0, len(citys)-1)
    new_path = swap(citys, a, b)
    orders_of_citys.append(new_path)

Thanks!




Aucun commentaire:

Enregistrer un commentaire