Apr-30-2017, 08:40 AM
I wrote this code about a year ago and barely understood it then, could someone please break down for me what my code is doing as I am highly confused. Very new to the Python programming language and am trying to get better.
I wrote this in Spyder if that helps.
Edit: This is a program to prove the fact that a descending sort is faster than an unordered sort in the well known bin packing problem.
I wrote this in Spyder if that helps.
Edit: This is a program to prove the fact that a descending sort is faster than an unordered sort in the well known bin packing problem.
from random import triangular import matplotlib.pyplot as plt import numpy as np def packing(books,boxSize = 1.0): totalBooks=len(books) boxes=np.zeros(totalBooks) for book in books: for i,box in enumerate(boxes): if book + box <= boxSize: boxes[i] += book break return boxes[boxes>0.0] def bookCreation(totalBooks, sorting): bookSet=[triangular(0, 1, 0.4) for i in range(totalBooks)] bookSet.sort(reverse=sorting) return bookSet def increaseBookTotal(totalBooks, increment = 5): sorting = [False, True] descending = [] unordered = [] nbooks=[] localBooks = totalBooks for sort in sorting: totalBooks = localBooks for i in range(100): boxesAverage = 0.0 if sort: nbooks.append(totalBooks) for j in range(100): boxes = packing(bookCreation(totalBooks, sort)).shape[0] boxesAverage+=(boxes-boxesAverage)/(1.0+j) if sort: descending.append(boxesAverage) else: unordered.append(boxesAverage) totalBooks += increment return [nbooks,descending, unordered] def percentage(totalBooks): nbooks,descending,unordered = increaseBookTotal(totalBooks) ratios=np.array(descending)/np.array(unordered) return nbooks,ratios totalBooks = 20 nbooks,ratios=percentage(totalBooks) plt.plot(nbooks,ratios) plt.ylabel('Improvement.') plt.xlabel('Number of Books.') plt.savefig('graph.png') plt.show()