Home > Blockchain >  Randomly generating different list from list
Randomly generating different list from list

Time:09-16

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!

CodePudding user response:

Your swap function is literally modifying the array, not returning a new array. So orders_of_citys contains five copies of the exact same array, and any time you. modify one of those arrays using swap, you're modifying all of them.

If you really want to see what's going on, change the last line to be

orders_of_citys.append(new_path[:])

which makes a copy of the array and then appends it to the variable.

CodePudding user response:

The new_path is actually a reference to citys, and you append the reference. Once the citys is changed, all the referred data will be changed too, so it have the same data.

And the solution is to make a deep copy of the array and append the copy.

from copy import deepcopy

# Other codes

def swap(c, a, b):
    d = deepcopy(c)
    value = d[a]
    d[a] = d[b]
    d[b] = value
    return d

The solution above is more easier. I'm late QwQ

  • Related