Skip to content

Instantly share code, notes, and snippets.

@huyhong
Created October 23, 2017 05:36
Show Gist options
  • Save huyhong/160fbe7aaffd5ea8a537cde4186027af to your computer and use it in GitHub Desktop.
Save huyhong/160fbe7aaffd5ea8a537cde4186027af to your computer and use it in GitHub Desktop.
fanny's knapsack problem
from ortools.algorithms import pywrapknapsack_solver
def main():
# Create the solver.
solver = pywrapknapsack_solver.KnapsackSolver(
pywrapknapsack_solver.KnapsackSolver.
KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,
'test')
values = [ 6361805,3746995,3760474,2911334,2237414,2298067,2106000,1964477,1886976,1550016,1843171,2015021,1809475,1607299,1603930,1172621,1745453,1533168,1479254,1644365,1600560,1334362,1290557,1344470,1213056,1266970,579571,1159142,970445,1098490,990662,815443,798595,6739,6739,454896 ]
weights = [[ 5912461,3345563,3145558,2398118,1690942,1539240,1410375,1315803,1263892,1253316,1194566,1186492,1028033,974392,966090,948161,917689,858290,846392,842972,841510,701554,698056,666170,659016,657174,517479,479020,387245,348384,297690,153346,28049,5449,5093,-165113 ]]
capacities = [6600000]
solver.Init(values, weights, capacities)
computed_value = solver.Solve()
packed_items = [x for x in range(0, len(weights[0]))
if solver.BestSolutionContains(x)]
packed_weights = [weights[0][i] for i in packed_items]
total_weight= sum(packed_weights)
print "Packed items: ", packed_items
print "Packed weights: ", packed_weights
print "Total value: ", computed_value
print "Total weight: ", total_weight
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment