Last active
February 27, 2019 15:39
-
-
Save ijan10/d494ed5f98df08f75c564e600cc2b9b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bin_packing(weights_list, max_weight_in_bin=None): | |
""" | |
:param weights_list: python list contains 'weight' for each key (or keys). weight represents the count of each key. | |
:param max_weight_in_bin: must be equal or bigger than the max weight in the weights_list. If None, using the max weight in list | |
:return: | |
""" | |
bin_id = 1 | |
weights_list = sorted(weights_list, key=itemgetter('weight'), reverse=True) | |
if max_weight_in_bin is None: | |
max_weight_in_bin = weights_list[0]['weight'] | |
for index, item in enumerate(weights_list): | |
if item.get(BIN_ID) is None: | |
sum_of_weight = 0 | |
for item_inner in weights_list[index:]: | |
if (item_inner.get(BIN_ID) is None) and (item_inner['weight'] + sum_of_weight <= max_weight_in_bin): | |
item_inner[BIN_ID] = bin_id | |
sum_of_weight += item_inner['weight'] | |
bin_id += 1 | |
return weights_list | |
list_join_key_weights = bin_packing(weights_list=list_join_key_weights) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment