Created
February 14, 2023 17:19
-
-
Save fabjan/529bb76ca1678ecd99155e0cae12fedb 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
# binpack.py | |
# Usage: binpack.py binsize csv_file | |
# | |
# binsize is the size of the bins to be used | |
# csv_file is the file containing the data to be packed | |
# | |
# The CSV file should have the following format: | |
# name, size | |
# name, size | |
# ... | |
# name, size | |
# | |
# The output is a table of bins mapping to the items in each bin. | |
import sys | |
import csv | |
import math | |
# a non-optimal bin packing algorithm | |
def pack(binsize, items): | |
items.sort(key=lambda item: item[1], reverse=True) | |
bins = [] | |
for item in items: | |
name = item[0] | |
size = item[1] | |
for bin in bins: | |
if bin[0] + size <= binsize: | |
bin[0] += size | |
bin[1].append(name) | |
break | |
else: | |
bins.append([size, [name]]) | |
return bins | |
# read the input file | |
def read_input(filename): | |
items = [] | |
with open(filename, 'r') as f: | |
reader = csv.reader(f) | |
for row in reader: | |
items.append([row[0], int(row[1])]) | |
return items | |
# write the output file | |
def write_output(bins): | |
for i in range(len(bins)): | |
for item in bins[i][1]: | |
print('bin' + str(i) + ', ' + item) | |
# main function | |
def main(): | |
if len(sys.argv) != 3: | |
print('Usage: binpack.py binsize csv_file') | |
sys.exit(1) | |
binsize = int(sys.argv[1]) | |
items = read_input(sys.argv[2]) | |
bins = pack(binsize, items) | |
write_output(bins) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment