Solving the Python knapsack problem with the greedy algorithm

[Knapsack Problem (Wikipedia)](https://ja.wikipedia.org/wiki/%E3%83%8A%E3%83%83%E3%83%97%E3%82%B5%E3%83%83 % E3% 82% AF% E5% 95% 8F% E9% A1% 8C) Greedy Method (Wikipedia) Solve with% B2% E6% B3% 95). Note that the solution obtained by the greedy algorithm is not always an exact solution. We would appreciate it if you could let us know if there are any deficiencies or suggestions for improvement regarding the code.

(About greedy algorithm from Wikipedia)

An example of application to the knapsack problem is shown below. In the case of this problem, it can be applied by dividing and evaluating each package.
Determine the valuation of each package in the knapsack problem. The number (value) ÷ (volume) is often used.
Select the package with the highest evaluation value.
If the baggage does not exceed the maximum capacity even if you put it in the knapsack, put it in the knapsack.
Select all packages in order of evaluation value and repeat the above operation.
The optimal solution cannot be obtained by the greedy algorithm for this problem.

It's like calculating the value per volume and packing from a great deal!

problem

4*x1 + 5*x2 + x3 + 3*x4 <= 6
xi = 0 or 1 (i = 1, 2, 3, 4)

Under the above conditions
7*x1 + 8*x2 + x3 + 2*x4
To maximize( x1, x2, x3, x4 )Use the greedy algorithm.

answer

import numpy as np
from pandas import DataFrame

#From constraints
weights = np.array([4, 5, 1, 3])
#From the objective function
values = np.array([7, 8, 1, 2])
#An array of x. The initial value is all 0. Set to 1 when adopted.
results = np.array([0, 0, 0, 0])
#Calculate the evaluation value.
evaluates = values/weights
#Put together in a DataFrame
target_df = DataFrame(np.c_[evaluates, weights, values, results], index=['x1', 'x2', 'x3', 'x4'], columns = ['evaluate', 'weight', 'value', 'result'])
#Sort in descending order by value of evaluate
target_df.sort_values('evaluate', ascending=False)

#The sum of the weights of the adopted items. Initial value 0.
weight_sum = 0

#Turn the loop from the one with the highest evaluation value
for index, target in target_df.iterrows():
    #Adopted after clearing the constraints
    if weight_sum + target['weight'] <= 6:
        weight_sum += target['weight']
        target['result'] = 1
        
print(target_df)
print("---answer---")
print(target_df['result'])

sort DataFrame sort is made up of sort_values. When I tried to do it with sort, I got DEPRECATED. Arrange in reverse order with ʻascending`. pandas.DataFrame.sort

When I tried to sort in reverse order only with numpy, it was done as follows.

import numpy as np
arr = np.array([[4, 2], [5, 2], [6, 4], [1, 3], [2, 3]])
arr = arr[ arr[:,0].argsort() ] #0th sort
arr = arr[::-1]
print(arr)

[[6 4]
 [5 2]
 [4 2]
 [2 3]
 [1 3]]

It's a little annoying. ..

result

    evaluate  weight  value  result
x1  1.750000     4.0    7.0     1.0
x2  1.600000     5.0    8.0     0.0
x3  1.000000     1.0    1.0     1.0
x4  0.666667     3.0    2.0     0.0
---answer---
x1    1.0
x2    0.0
x3    1.0
x4    0.0
Name: result, dtype: float64

Therefore, ( x1, x2, x3, x4 ) = ( 1, 0, 1, 0 )

Recommended Posts

Solving the Python knapsack problem with the greedy algorithm
The first algorithm to learn with Python: FizzBuzz problem
A memo that solves the knapsack problem by the greedy algorithm
Solving the paraboloid minimization problem with OpenMDAO
Search the maze with the python A * algorithm
Solve the Python knapsack problem with a branch and bound method
Algorithm learned with Python 14th: Tic-tac-toe (ox problem)
Solving the N Queen problem with combinatorial optimization
Solving the N Queens problem with combinatorial optimization
Solving the Lorenz 96 model with Julia and Python
Find the shortest path with the Python Dijkstra's algorithm
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
Basic information Write the 2018 fall algorithm problem in Python
Try to solve the internship assignment problem with Python
The 14th offline real-time writing reference problem with Python
Solving the iris problem with scikit-learn ver1.0 (logistic regression)
I tried to solve the problem with Python Vol.1
[Python] Dynamic programming knapsack problem
Solving Sudoku with Python (Incomplete)
Solving Sudoku with Python (Part 2)
[Python3] Dijkstra's algorithm with 14 lines
Call the API with python3.
ABC188 C problem with python3
ABC187 C problem with python
Finding a solution to the N-Queen problem with a genetic algorithm (2)
Solve the spiral book (algorithm and data structure) with python!
Finding a solution to the N-Queen problem with a genetic algorithm (1)
Extract the xz file with python
Get the weather with Python requests
Find the Levenshtein Distance with python
Hit the Etherpad-lite API with Python
I liked the tweet with python. ..
Implementation of Dijkstra's algorithm with python
[AtCoder commentary] Win the ABC165 C problem "Many Requirements" with Python!
Solving the Maze with Python-Supplement to Chapter 6 of the Algorithm Quick Reference-
I wanted to solve the ABC164 A ~ D problem with Python
Solving Knapsack Problems with Google's OR-Tools-Practicing the Basics of Combinatorial Optimization Problems
Solve the subset sum problem with a full search in Python
Make the Python console covered with UNKO
The 16th offline real-time how to write problem was solved with Python
Algorithm learned with Python 10th: Binary search
Algorithm learned with Python 5th: Fibonacci sequence
[Python] Set the graph range with matplotlib
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
Compute the partition function with the sum-product algorithm
Behind the flyer: Using Docker with Python
Algorithm learned with Python 7th: Year conversion
Try the Variational-Quantum-Eigensolver (VQE) algorithm with Blueqat
Check the existence of the file with python
Algorithm learned with Python 8th: Evaluation of algorithm
The 16th offline real-time how to write reference problem to solve with Python
[Python] Get the variable name with str
[Python] Round up with just the operator
Display Python 3 in the browser with MAMP
Python algorithm
Algorithm learned with Python 4th: Prime numbers
Let's read the RINEX file with Python ①
Try to solve the traveling salesman problem with a genetic algorithm (Theory)
Working with OpenStack using the Python SDK
Algorithm learned with Python 2nd: Vending machine
Algorithm learned with Python 19th: Sorting (heapsort)