Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update knapsackproblem.py #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 56 additions & 30 deletions knapsackproblem.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,56 @@
items =[
["A",24,12,"complete"],
["B",13,7,"complete"],
["C",23,11,"complete"],
["D",15,8,"complete"],
["E",16,9,"complete"],
["F",15,3,"complete"]]
sum = 0
size = 14
profit = 0
new = sorted(items,key=lambda x: x[1],reverse = True)
final =[]
# new.sort(reverse = True)
for i in range(0,len(items)):
while(sum<size):
final.append(new[i])
sum +=new[i][2]
profit += new[i][1]
new.remove(new[i])
if(sum>size):
sum = size
final[len(final)-1][3]='partial'
print("\n")
for i in range(len(final)):
print(final[i])
print("\n")
print(profit)
print("\n")

print(sum)

#greedyoption
#program to solve fractional
# Knapsack Problem
class ItemValue:

"""Item Value DataClass"""
def __init__(self, wt, val, ind):
self.wt = wt
self.val = val
self.ind = ind
self.cost = val // wt

def __lt__(self, other):
return self.cost < other.cost

# Greedy Approach
class FractionalKnapSack:

"""Time Complexity O(n log n)"""
@staticmethod
def getMaxValue(wt, val, capacity):

"""function to get maximum value """
iVal = []
for i in range(len(wt)):
iVal.append(ItemValue(wt[i], val[i], i))

# sorting items by value
iVal.sort(reverse = True)

totalValue = 0
for i in iVal:
curWt = int(i.wt)
curVal = int(i.val)
if capacity - curWt >= 0:
capacity -= curWt
totalValue += curVal
else:
fraction = capacity / curWt
totalValue += curVal * fraction
capacity = int(capacity - (curWt * fraction))
break
return totalValue

# Driver Code
if __name__ == "__main__":
wt = [10, 40, 20, 30]
val = [60, 40, 100, 120]
capacity = 50

maxValue = FractionalKnapSack.getMaxValue(wt, val, capacity)
print("Maximum value in Knapsack =", maxValue)