Skip to content

Instantly share code, notes, and snippets.

@joe-henke
Created February 25, 2016 06:17
Show Gist options
  • Save joe-henke/da1b7a91fa1c8752351a to your computer and use it in GitHub Desktop.
Save joe-henke/da1b7a91fa1c8752351a to your computer and use it in GitHub Desktop.
Greedy Fractional Knapsack
# Uses python3
import sys
# returns the ratio of value to weight
def getValueRatio(item):
return (item[0]/item[1])
def checkInput(n, min, max):
if n<min or n>max:
return True
return False
def getOptimalValue(capacity, weights, values):
value = 0
weightCapacity = capacity
vwRatios = zip(values, weights)
vwRatiosSorted = sorted(vwRatios, key=getValueRatio, reverse=True)
for i in vwRatiosSorted:
iWeight = i[1]
if weightCapacity == 0:
return value
a = min(iWeight, weightCapacity)
value = value + a * (getValueRatio(i))
weightCapacity = weightCapacity - a
return value
def checkParameters(n, capacity, values, weights):
# check that n and capacity fit the parameters
if checkInput(n, 1, 1000):
sys.exit(0)
if checkInput(capacity, 0, 2000000):
sys.exit(0)
# check that there are enough elements
if len(values) != n:
sys.exit(0)
if len(weights) != n:
sys.exit(0)
#check that the values in the arrays fit the parameters
for i in range(n):
if checkInput(values[i], 0, 2000000):
sys.exit(0)
if checkInput(weights[i], 1, 2000000):
sys.exit(0)
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
checkParameters(n, capacity, values, weights)
opt_value = getOptimalValue(capacity, weights, values)
print("{:.10f}".format(opt_value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment