#!/usr/bin/env python # # Program to read and print a file # import random # evaluate a candidate solution # inputs: weight array, value array, # and boolean vector where 1 in position i indicates that item i # will be taken. # outputs: total weight taken in this choice and total value def evalcand(myweights, myvalues, mychoices): sumweights = 0 sumvalues = 0 i = 0 while(i < len(mychoices)): if(mychoices[i] == 1): sumweights+= myweights[i] sumvalues+= myvalues[i] i+=1 return (sumweights, sumvalues) # generate a candidate # consisting of a boolean array of length mylen # input: mylen # ouput: the array def gencand(mylen): arr = [] i = 0 while(i < mylen): x = random.random() if(x > 0.75): arr.append(1) else: arr.append(0) i+=1 return (arr) # EXECUTION file = open("knapinput","r") text = file.readlines() file.close() print text[0] totweight = int(text[0]) weights = [] values = [] i = 1 while(i < len(text)): x = text[i].split(" ") weights.append(int(x[0])) values.append(int(x[1])) i+=1 myarr = gencand(len(weights)) print evalcand(weights, values, myarr)