python: sync multiple_knapsack samples

This commit is contained in:
Mizux Seiha
2021-12-01 16:04:53 +01:00
parent 1528945dbc
commit 628ea0465c
2 changed files with 23 additions and 29 deletions

View File

@@ -97,7 +97,7 @@ def main():
bin_weight += data['weights'][i]
bin_value += data['values'][i]
print(f'Packed bin weight: {bin_weight}')
print(f'Packed bin value: {bin_value}')
print(f'Packed bin value: {bin_value}\n')
total_weight += bin_weight
print(f'Total packed weight: {total_weight}')
else:

View File

@@ -45,23 +45,16 @@ def main():
# Variables.
# [START variables]
# x[i, b] = 1 if item i is packed in bin b.
x = {}
for i in data['all_items']:
for b in data['all_bins']:
x[i, b] = model.NewBoolVar(f'x_{i}_{b}')
max_value = sum(data['values'])
# value[b] is the value of bin b when packed.
value = [
model.NewIntVar(0, max_value, 'value_%i' % b) for b in data['all_bins']
]
for b in data['all_bins']:
model.Add(value[b] == sum(
x[i, b] * data['values'][i] for i in data['all_items']))
# [END variables]
# Constraints.
# [START constraints]
# Each item can be in at most one bin.
# Each item is assigned to at most one bin.
for i in data['all_items']:
model.Add(sum(x[i, b] for b in data['all_bins']) <= 1)
@@ -72,40 +65,41 @@ def main():
for i in data['all_items']) <= data['bin_capacities'][b])
# [END constraints]
# Objective.
# [START objective]
# Maximize total value of packed items.
model.Maximize(sum(value))
objective = []
for i in data['all_items']:
for b in data['all_bins']:
objective.append(cp_model.LinearExpr.Term(x[i, b], data['values'][i]))
model.Maximize(cp_model.LinearExpr.Sum(objective))
# [END objective]
# [START solver]
solver = cp_model.CpSolver()
# [END solver]
# [START solve]
solver = cp_model.CpSolver()
status = solver.Solve(model)
# [END solve]
# [START print_solution]
if status == cp_model.OPTIMAL:
print(f'Total packed value: {solver.ObjectiveValue()}')
total_weight = 0
total_value = 0
for b in data['all_bins']:
print('Bin', b, '\n')
print(f'Bin {b}')
bin_weight = 0
bin_value = 0
for idx, val in enumerate(data['weights']):
if solver.Value(x[(idx, b)]) > 0:
print('Item', idx, '- Weight:', val, ' Value:',
data['values'][idx])
bin_weight += val
bin_value += data['values'][idx]
print('Packed bin weight:', bin_weight)
print('Packed bin value:', bin_value, '\n')
for i in data['all_items']:
if solver.Value(x[i, b]) > 0:
print(f"Item {i} weight: {data['weights'][i]} value: {data['values'][i]}")
bin_weight += data['weights'][i]
bin_value += data['values'][i]
print(f'Packed bin weight: {bin_weight}')
print(f'Packed bin value: {bin_value}\n')
total_weight += bin_weight
total_value += bin_value
print('Total packed weight:', total_weight)
print('Total packed value:', total_value)
# [END solutions_printer]
print(f'Total packed weight: {total_weight}')
else:
print('The problem does not have an optimal solution.')
# [END print_solution]
if __name__ == '__main__':