I have some code that takes n groups of states and then creates multiple "neighbors" by swapping states between groups randomly.
from random import randint as rand
groups = [['VT', 'TX', 'HI', 'AR', 'PA', 'OK', 'AK', 'MI', 'ND', 'ID', 'NY', 'WV', 'FL', 'UT'],
['MO', 'MA', 'SD', 'NE', 'GA', 'MN', 'SC', 'CA', 'RI', 'AZ', 'NH', 'MS', 'AL', 'WI', 'GU', 'CT', 'MT', 'TN', 'OH', 'OR', 'IA'],
['NV', 'KY', 'NM', 'KS', 'IN', 'LA', 'DE', 'MD', 'CO', 'IL', 'VA', 'NC', 'WY', 'NJ', 'WA', 'ME']]
def hill_climb_nbr(groups,nbr_size):
#swap one state in and out of each group
group_list = []
for g in range(0,nbr_size):
temp_val = []
groups_copy = groups
for i in range(0,len(groups)):
rand_num = rand(0,len(groups[i])-1)
temp_val.append(groups[i][rand_num])
groups_copy[i].pop(rand_num)
print(rand_num)
for j in range(0,len(temp_val)):
groups_copy[j].append(temp_val[j-1])
print(groups_copy)
print('group_list')
group_list.append(groups_copy)
print(group_list)
return group_list
hill_climb_nbr(groups,3)
Here is an example of input:
[['VT', 'TX', 'HI', 'AR', 'PA', 'OK', 'AK', 'MI', 'ND', 'ID', 'NY', 'WV', 'FL', 'UT'],
['MO', 'MA', 'SD', 'NE', 'GA', 'MN', 'SC', 'CA', 'RI', 'AZ', 'NH', 'MS', 'AL', 'WI', 'GU', 'CT', 'MT', 'TN', 'OH', 'OR', 'IA'],
['NV', 'KY', 'NM', 'KS', 'IN', 'LA', 'DE', 'MD', 'CO', 'IL', 'VA', 'NC', 'WY', 'NJ', 'WA', 'ME']]
The output of hill_climb_nbr(groups,3)
where groups is the list of lists shown above is this:
[[['VT', 'TX', 'HI', 'AR', 'PA', 'OK', 'AK', 'MI', 'ND', 'ID', 'NY', 'WV', 'FL', 'UT'],
['MO', 'MA', 'SD', 'NE', 'GA', 'MN', 'SC', 'CA', 'RI', 'AZ', 'NH', 'MS', 'AL', 'WI', 'GU', 'CT', 'MT', 'TN', 'OH', 'OR', 'IA'],
['NV', 'KY', 'NM', 'KS', 'IN', 'LA', 'DE', 'MD', 'CO', 'IL', 'VA', 'NC', 'WY', 'NJ', 'WA', 'ME']],
[['VT', 'TX', 'HI', 'AR', 'PA', 'OK', 'AK', 'MI', 'ND', 'ID', 'NY', 'WV', 'FL', 'UT'],
['MO', 'MA', 'SD', 'NE', 'GA', 'MN', 'SC', 'CA', 'RI', 'AZ', 'NH', 'MS', 'AL', 'WI', 'GU', 'CT', 'MT', 'TN', 'OH', 'OR', 'IA'],
['NV', 'KY', 'NM', 'KS', 'IN', 'LA', 'DE', 'MD', 'CO', 'IL', 'VA', 'NC', 'WY', 'NJ', 'WA', 'ME']],
[['VT', 'TX', 'HI', 'AR', 'PA', 'OK', 'AK', 'MI', 'ND', 'ID', 'NY', 'WV', 'FL', 'UT'],
['MO', 'MA', 'SD', 'NE', 'GA', 'MN', 'SC', 'CA', 'RI', 'AZ', 'NH', 'MS', 'AL', 'WI', 'GU', 'CT', 'MT', 'TN', 'OH', 'OR', 'IA'],
['NV', 'KY', 'NM', 'KS', 'IN', 'LA', 'DE', 'MD', 'CO', 'IL', 'VA', 'NC', 'WY', 'NJ', 'WA', 'ME']]]
It is a strain to see, but it is just the same list of lists repeated three times.
While trying to diagnose the problem, I found that groups_copy
looks correct right before the group_list.append(groups_copy)
. Somehow the final group_list
turns out to be the last groups_copy
repeated nbr_size
times instead of each iteration of groups_copy
.
I've been looking at this for a few hours now and I'm about to loose my mind. Does anything stand out to you as to where the issue is?