Last active
July 20, 2020 04:14
-
-
Save fchristofrank/fdfc7688c6d47c4538d37e8dfd841d55 to your computer and use it in GitHub Desktop.
Fractional_knapsack algorithm with python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fractional_knapsack(VperW,W): | |
'''This function implements the fractional knapsack problem''' | |
i = 0 | |
Value = 0 | |
count = 0 | |
# sort to reduce the time complexity. You need not find the max in the list | |
# at every iteration | |
VperW = sorted(VperW.items(),reverse =True) | |
while i<n and W != 0: | |
a = min(W,VperW[i][1][1]) | |
W = W - a | |
Value = Value + VperW[i][0]*a | |
i += 1 | |
print("Final Value of W ",W) | |
print("Maximum Value By Fractional Knapsack",Value) | |
if __name__ == "__main__": | |
# n takes number of input and W is the max weight | |
# INPUT FORMAT EX: 3 50 | |
n,W = map(int,input().split()) | |
#CREATE A DICT(you can create a array also) | |
VperW = {} | |
for i in range(n): | |
val = list(map(int,input().split())) | |
key = val[0]/val[1] | |
VperW[key] = val | |
fractional_knapsack(VperW,W) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment