From the course: Advanced Algorithmic Thinking with Python
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
The knapsack problem: Python implementation - Python Tutorial
From the course: Advanced Algorithmic Thinking with Python
The knapsack problem: Python implementation
- [Instructor] On branch 04_05, you'll find a file called zero_one_knapsack.py. This is an implementation of the 0/1 knapsack problem in Python. On line 1, I've imported a module called tabulate, which is great for creating attractive tables. Now you don't need to use it. If you do want to use it, you'll have to import it using pip. Otherwise, I'll show you how to not use it in a moment. From lines 4 through 19, we have our main knapsack function. Now this takes three arguments. That's the maximum capacity. And then two lists. We have our weights list and our values list. Then we're just creating a reference we can use to the length of our weights and values. That's the number of items, which needs to be the same as a number of weights. And then line 6, we use a list comprehension to create an empty table. So what we're doing on line 6 is we're basically just creating an empty table, like at the start of when we…
Contents
-
-
-
-
-
-
Introduction to dynamic programming56s
-
(Locked)
Top-down dynamic programming example2m 26s
-
(Locked)
Bottom-up dynamic programming example47s
-
(Locked)
The knapsack problem: Theory5m 7s
-
(Locked)
The knapsack problem: Python implementation3m 54s
-
(Locked)
Challenge: The knapsack problem36s
-
(Locked)
Solution: The knapsack problem16s
-
-
-