summaryrefslogtreecommitdiffstats
path: root/01-knapsack/solver.py
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-07-03 14:29:47 +0200
committerJérémy Zurcher <jeremy@asynk.ch>2013-07-03 14:29:47 +0200
commita4a6f22f3fd665f224d9f199d2326d3be43141ba (patch)
tree2a9dab5347085f772b624fa56f91e547a3e594b6 /01-knapsack/solver.py
parent1a1515b5eb60e4dc049256d0498f4fb0f0c29b23 (diff)
downloadcoursera-a4a6f22f3fd665f224d9f199d2326d3be43141ba.zip
coursera-a4a6f22f3fd665f224d9f199d2326d3be43141ba.tar.gz
Discrete : 01-knapsack: dynamic programming solver + malloc error when to many values
Diffstat (limited to '01-knapsack/solver.py')
-rwxr-xr-x01-knapsack/solver.py49
1 files changed, 16 insertions, 33 deletions
diff --git a/01-knapsack/solver.py b/01-knapsack/solver.py
index 81a6d79..ffb1852 100755
--- a/01-knapsack/solver.py
+++ b/01-knapsack/solver.py
@@ -1,47 +1,30 @@
-#!/usr/bin/python2.7
+#!/usr/bin/python2
# -*- coding: utf-8 -*-
+import os
+from subprocess import Popen, PIPE
-def solveIt(inputData):
- # Modify this code to run your optimization algorithm
-
- # parse the input
- lines = inputData.split('\n')
- firstLine = lines[0].split()
- items = int(firstLine[0])
- capacity = int(firstLine[1])
+def solveIt(inputData):
- values = []
- weights = []
+ # Writes the inputData to a temporay file
- for i in range(1, items+1):
- line = lines[i]
- parts = line.split()
+ tmpFileName = 'tmp.data'
+ tmpFile = open(tmpFileName, 'w')
+ tmpFile.write(inputData)
+ tmpFile.close()
- values.append(int(parts[0]))
- weights.append(int(parts[1]))
+ # Runs the command: java Solver -file=tmp.data
- items = len(values)
+ process = Popen(['./ks_dp', tmpFileName],
+ stdout=PIPE)
+ (stdout, stderr) = process.communicate()
- # a trivial greedy algorithm for filling the knapsack
- # it takes items in-order until the knapsack is full
- value = 0
- weight = 0
- taken = []
+ # removes the temporay file
- for i in range(0, items):
- if weight + weights[i] <= capacity:
- taken.append(1)
- value += values[i]
- weight += weights[i]
- else:
- taken.append(0)
+ os.remove(tmpFileName)
- # prepare the solution in the specified output format
- outputData = str(value) + ' ' + str(0) + '\n'
- outputData += ' '.join(map(str, taken))
- return outputData
+ return stdout.strip()
import sys