Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 88562f1

Browse files
added 0-1 Knapsack
1 parent 385db73 commit 88562f1

File tree

3 files changed

+44
-8
lines changed

3 files changed

+44
-8
lines changed
Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
from typing import List
22

3+
34
class Solution:
45
def singleNumber(self, nums: List[int]) -> int:
56
binSum = 0
6-
mask = bin((1<<32) -1)
7+
mask = bin((1<<32) -1)
78
uniqueBin = ""
89
for num in nums:
9-
binary = int(bin(num & int(mask,2))[2:])
10+
binary = int(bin(num & int(mask,2))[2:])
1011
print(num, "=", binary)
1112
binSum += binary
1213
print("sum =", binSum)
@@ -17,15 +18,15 @@ def singleNumber(self, nums: List[int]) -> int:
1718
uniqueBin += "0"
1819
print("unique number in binary:", uniqueBin)
1920
if int(uniqueBin, 2) > 2**31:
20-
uniqueBin = str(bin(int(uniqueBin,2)-1))
21+
uniqueBin = str(bin(int(uniqueBin,2)-1))
2122
print(uniqueBin)
22-
print(bin((~int(uniqueBin, 2) & int(mask,2))))
23-
return -(~int(uniqueBin, 2) & int(mask,2))
23+
print(bin((~int(uniqueBin, 2) & int(mask,2))))
24+
return -(~int(uniqueBin, 2) & int(mask,2))
2425
return int(uniqueBin, 2)
25-
26+
2627

2728
# test driver
2829
sol = Solution()
29-
input = [-19,-46,-19,-46,-9,-9,-19,17,17,17,-13,-13,-9,-13,-46,-28]
30+
input = [2, 3, 2, 2]
3031
print("Input:", input)
31-
print("Output:", sol.singleNumber(input))
32+
print("Output:", sol.singleNumber(input))
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# 0-1 Knapsack
2+
3+
## Problem:
4+
5+
Given `weights`: list of weights where `weights[i]` represents the weight of `i-th` item,
6+
`values` : list of values where `values[i]` represents the value of `i-th` item,
7+
and `W`, total weight available,
8+
Find the maximum values that can be achieved within the limit of total weight.
9+
10+
## Example:
11+
12+
```
13+
Input: weights = [4, 5, 2, 3]
14+
values = [5, 3, 2, 4]
15+
W = 7
16+
Output: 9
17+
```
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def knapsack(weights, values, W):
2+
dp = [[0 for _ in range(W+1)] for _ in range(len(weights)+1)]
3+
# print(dp)
4+
for i in range(1, len(dp)):
5+
for j in range(1, len(dp[i])):
6+
if weights[i-1] <= j:
7+
dp[i][j] = max(dp[i-1][j], dp[i-1]
8+
[j-weights[i-1]] + values[i-1])
9+
else:
10+
dp[i][j] = dp[i-1][j]
11+
# print(dp)
12+
return dp[-1][-1]
13+
14+
15+
weights = [4, 5, 2, 3]
16+
values = [5, 3, 2, 4]
17+
W = 7
18+
print(knapsack(weights, values, W))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /