I began using Python last week and am struggling to get this piece of code to work.
For context, I am trying to find heuristic ways to solve the group balancing problem. In the problem, there are n items which are split into k groups, each item with a unique weight, and the aim is to divide them into the groups such that the groups are as close to each other in weight as possible. For every solution (i.e. – choice of groups) there is a cost, so we wish to minimise the cost.
I have solved the problem using a Hill Climbing algorithm and Simulated Annealing, and am now attempting to solve it using Tabu Search. The first step is to look through all of the neighbourhoods of the solution and pick the best one. Here, if we have a solution, a neighbourhood is just moving an item from one group to another. The method I’m using is to choose an item, delete it and then append it onto the end of another group, and run that over all items and all groups.
The code I’m using for this is below:
def best_neighbour(current_groups):
current_cost = n*n*n # Set a high initial cost
for K in range(0, k-1): # Do it over all groups
L = len(current_groups[K]) # Find the number of elements in the group
for i in range(0, L-1): # Do it for each item in the group
for j in range(0, k-1): # For each group we can move to
obj = current_groups[K][i] # Copy the element we are working with
new_groups = [group[:] for group in current_groups] # Make a copy of the current groups
del new_groups[K][i] # Delete the selected item from the current group
new_groups[j].append(obj) # Add the selected item to the new group
new_cost = calculate_cost(new_groups, Mean) # Calculate the cost of the new solution
if check_feasibility(new_groups, k-1): # Check if the solution is feasible
if new_cost < current_cost: # If the new cost is the lowest of the costs of all groups tested so far
updated_groups = new_groups # Replace the groups with the new groups
current_cost = new_cost # Replace the cost with the cost of the new groups
return updated_groups
I’ve tried to label as best as possible what each step of the code is trying to do. My problem is that the code returns a value which isn’t the best neighbourhood, but is instead just the first item deleted from the first group and then re-appended onto the first group (which is the first iteration of the intended loop). Therefore, I’m fairly sure that it isn’t looping as intended.
Any help on how I could get the code to loop would be greatly appreciated!
MarkH9664 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1