# python implementation of knapsack problem

Keywords: REST Python

Now I'm learning the algorithm course of Mr. Wang Xiaohua. I won't write C + + for the time being, so let's implement it in Python first.

The knapsack problem is a variety of items, each of which has only one item. Here we use an extremely simple greedy method to achieve:
It can be based on weight, value or value density, just change the sorting basis.

```import pandas as pd
import numpy as np

wi = [35, 30, 60, 50, 40, 10, 25]
pi = [10, 40, 30, 50, 35, 40, 30]
status = [0, 0, 0, 0, 0, 0, 0]
data = pd.DataFrame(columns=["weight", "price", "density"])
data["weight"] = wi
data["price"] = pi
data["density"] = data["price"] / data["weight"]
data["status"] = status
reason = "price"  # weight or density
rest = 150
values = 0
data = data.sort_values(by=reason, ascending=False).reset_index().drop(["index"], axis=1)
index = 0

def best_weight(data, reason, rest, values, index):
#print(reason, rest, values, index)

if rest < np.min(data.loc[range(index, len(data)), "weight"]) or (index == len(data)):
return values
else:
if rest >= data["weight"][index]:
data.loc[index, 'status'] = 1 # With data["status"][index] = 1, there will be warning
rest = rest - data["weight"][index]
values = values + data["price"][index]
index = index + 1
values=best_weight(data, reason, rest, values, index)
return values
else:
index = index + 1
values=best_weight(data, reason, rest, values, index)
return values
yyt = best_weight(data, reason, rest, values, index)
print(yyt)

```

I realized that return didn't only appear at the end of the recursion!

In the process of writing code, some usages are often uncertain. Here is a summary:
Determine whether dataframe is empty: df.empty
dataframe sorting: df.sort_values(by="",ascending=False)
dataframe delete by line: df=df[df[""]==1]
datafram can delete the specified row and column with drop
Assign with dataframe.loc

Posted by wobbit on Sun, 01 Dec 2019 13:59:38 -0800