def test_knapsack(self): self.assertEqual(22, knapsack([1, 6, 10, 16], [1, 2, 3, 5], 7)) self.assertEqual(17, knapsack([1, 6, 10, 16], [1, 2, 3, 5], 6)) self.assertEqual(22, knapsack2([1, 6, 10, 16], [1, 2, 3, 5], 7)) self.assertEqual(17, knapsack2([1, 6, 10, 16], [1, 2, 3, 5], 6)) self.assertEqual(22, knapsack3([1, 6, 10, 16], [1, 2, 3, 5], 7)) self.assertEqual(17, knapsack3([1, 6, 10, 16], [1, 2, 3, 5], 6)) self.assertEqual(0, knapsack3([1, 6, 10, 16], [1, 2, 3, 5], 0))
def main(): kn = knapsack() while (True): print("Witamy w menu!!") print( " 0 - Wyjscie\n 1 - plecakowy\n 2 - MST\n 3 - CPM\n 4 - Przepływ w sieciach\n 5 - poroblem szeregowania\n 6 - kolorowanie (algorytm Browna)" ) print("Wybierz program: ", sep="", end="") program = int(input()) if program == 0: print("Pa, pa!!") break if program == 1: kn.back() if program == 2: print("Program w budowie...") if program == 3: print("Program w budowie...") if program == 4: print("Program w budowie...") if program == 5: print("Program w budowie...") if program == 6: print("Program w budowie...") print()
def knapsack_of_capturable_planets(universe, planet, distance): '''Returns the set of planets which can currently be captured which have the the most growth in `distance` turns''' candidates = [ p for p in universe.not_my_planets if (planet.distance(p) < distance) and ( p.turns_till_profit < TURNS_TO_PROFIT_MAX) ] #log.error("distance: %s, LIST: %s " % (distance, candidates)) table = [] for c in candidates: nearest_enemy_planet = c.find_nearest_neighbor(owner=player.ENEMIES) #log.info("distance to enemy: %s " % (nearest_enemy_planet.distance(c))) #log.info("planet.turns_till_profit: %s " % (c.turns_till_profit)) #Check if planet will be caputured before our ships will get there future_planet = c.in_future(planet.distance(c)) #log.info("future_planet CANIDATE: %s " % (future_planet)) if future_planet.owner == player.ME: continue #Use the future state in case other fleets are in root cost = future_planet.ship_count + 1 value = (distance - c.distance(planet)) * c.growth_rate table.append((c, cost, value)) return knapsack(table, planet.ship_count)
def optimal_solution(self): total_reward, choices = knapsack.knapsack( self.weights, self.values).solve(self.max_weight) xs = np.zeros(self.K) for i in choices: xs[i] = 1 return total_reward, xs
def knap(self, servers, spectr): result = [-1]*len(spectr) length = len(spectr) spectr = [x+1 for x in spectr] # size = [nx.degree(self.graph, node) for node in self.graph.nodes()] size = [self.graph.node[x]['size'] for x in self.graph.nodes()] capacity = [x.capacity for x in self.servers] print "capacity: " + str(capacity) weight = spectr print "size" print size for i in range(0, len(self.servers)): print "weight" print weight res = knapsack.knapsack(size, weight).solve(capacity[i]) print res res = res[1] for j in res: # print "node {0} for id {1}".format(self.graph.nodes()[j], j) result[j] = i weight[j] = 0 print "result" print result return result
def max_reward_to_go(self): remaining_weight_capacity = self.max_weight - np.sum( self.weights[self.xs == 1]) max_rtg, _ = knapsack.knapsack( self.weights[self.xs != 1], self.values[self.xs != 1]).solve(remaining_weight_capacity) return max_rtg
def select_keyshots(video_info, pred_score): """ input: video_info: specific video of *.h5 file pred_score: [320] key frame score in every frames """ N = video_info['length'][()] # scalar, video original length cps = video_info['change_points'][( )] # shape [n_segments,2], stores begin and end of each segment in original length index weight = video_info['n_frame_per_seg'][( )] # shape [n_segments], number of frames in each segment pred_score = pred_score.to( "cpu").detach().numpy() # GPU->CPU, requires_grad=False, to numpy pred_score = upsample(pred_score, N) # Use Nearest Neighbor to extend from 320 to N pred_value = np.array([pred_score[cp[0]:(cp[1] + 1)].mean() for cp in cps]) # [n_segments] _, selected = knapsack( pred_value, weight, int(0.15 * N) ) # selected -> [66, 64, 51, 50, 44, 41, 40, 38, 34, 33, 31, 25, 24, 23, 20, 10, 9] selected = selected[:: -1] # inverse the selected list, which seg is selected key_labels = np.zeros(shape=(N, )) for i in selected: key_labels[cps[i][0]:(cps[i][1] + 1)] = 1 # assign 1 to seg # pred_score: shape [n_segments] # selected: which seg is selected # key_labels: assign 1 to selected seg return pred_score.tolist(), selected, key_labels.tolist()
def get_col(basis, weight, max_len): value = basis.sum(axis=0) n = len(weight) configuration = np.zeros(n, dtype=int32) table = -np.ones(max_len + 1) optimal_conf = np.zeros((max_len + 1, n), dtype=int32) reduced_cost, column = knapsack(weight, value, max_len, n, configuration, table, optimal_conf) return reduced_cost, column
def knap(size, weight, capacity): """ size = [21, 11, 15, 9, 34, 25, 41, 52] weight = [22, 12, 16, 10, 35, 26, 42, 53] capacity = 100 knapsack.knapsack(size, weight).solve(capacity) """ return knapsack.knapsack(size, weight).solve(capacity)
def warehouse(max_weight: int, items: List[Item]) -> Tuple[int, set]: """ :param max_weight: the capacity of the warehouse :param items: a list of item, each has a name and a weight :return: a set of items, two item can be the same, the total weights <= W, and the total name is maximized """ copies = get_max_object_copies(items, max_weight) return knapsack(max_weight, copies)
def calculate_sets_of_players(skaters, goalies, util, limit, type="knapsack"): if type == "knapsack": return knapsack(skaters, goalies, util, limit) elif type == "brute_force": return brute_force(skaters, goalies, util, limit) # , 100, 4000) else: raise ValueError( "Invalid type for calculate_set_of_players: " + type + ", choose either knapsack or brute_force.")
def test_assigment2(self): print("Testing Assigment 2") test_input = 'greedy_algorithms_mst_dynamic_programming/week4/knapsack/assigment2.txt' test_case = read_items(test_input, " ") final_answer = knapsack(test_case[0], test_case[1]) print("Final Answer: {}".format(final_answer))
def test_small_knapsack(self): v = [3, 2, 4, 4] w = [4, 3, 2, 3] self.assertEqual(knapsack(v, w, 6), 8) v = [4, 2, 6, 1, 2] w = [12, 1, 4, 1, 2] self.assertEqual(knapsack_re(v, w, 15), 11)
def main(): weights, values = parse(sys.argv[1]) weight_bound = int(prompt("Weight Bound")) matrix = knapsack(weights, values, weight_bound) score = matrix[-1][-1] ##Best score will always be in the last position items = walkback(weights, values, matrix) print "The best score is %d and the items are %s" % (score, str(items))
def getSolution(self, batchArray): out = [] for batch in range(batchArray.shape[0]): out.append( knapsack.knapsack(batchArray[batch, :, 0].tolist(), batchArray[batch, :, 1].tolist()).solve(self.capacity)) return np.array(out)
def show_answer(message): global W, val, itens, wt chat_id = message.chat.id W = int(message.text) answer = knapsack(W, wt, val, itens, len(val)) backpack = " ".join(answer[0]) total_value = answer[1] bot.send_message(chat_id, f"Leve na mochilas os seguites itens: {backpack}") bot.send_message(chat_id, f"Sua mochila terá o valor máximo de {total_value}")
def test_sad(obj, file_name, max_mass): start = datetime.datetime.now() best = sad.knapsack(obj, max_mass) exec_time = datetime.datetime.now() - start print("Tested %s with max_mass=%s in %s" % (file_name, max_mass, exec_time)) print(" optimum: %s" % best) r = sad.greedy(obj, max_mass, sad.best_price) print(" best price: %s / %.1f%%" % (r, 100.*(best-r)/best)) r = sad.greedy(obj, max_mass, sad.worst_mass) print(" worst mass: %s / %.1f%%" % (r, 100.*(best-r)/best)) r = sad.greedy(obj, max_mass, sad.best_ratio) print(" best ratio: %s / %.1f%%" % (r, 100.*(best-r)/best))
def call_knapsack(id): luggage = list(mongo_api.Luggage.find({'flight_id': mongo_api.get_obj_id(id)})) result = knapsack.knapsack(luggage) for bag in result: mongo_api.Luggage.find_one_and_update( {'_id': bag['_id']}, { '$set': { 'container_no': bag['container_no'] } } ) return redirect(url_for('luggage_page', fname = id))
def select_keyshots(video_info, pred_score): N = video_info['length'][()] cps = video_info['change_points'][()] weight = video_info['n_frame_per_seg'][()] pred_score = np.array(pred_score.cpu().data) pred_score = upsample(pred_score, N) pred_value = np.array([pred_score[cp[0]:cp[1]].mean() for cp in cps]) _, selected = knapsack(pred_value, weight, int(0.15 * N)) selected = selected[::-1] key_labels = np.zeros(shape=(N, )) for i in selected: key_labels[cps[i][0]:cps[i][1]] = 1 return pred_score.tolist(), selected, key_labels.tolist()
def test_sad(obj, file_name, max_mass): start = datetime.datetime.now() best = sad.knapsack(obj, max_mass) exec_time = datetime.datetime.now() - start print("Tested %s with max_mass=%s in %s" % (file_name, max_mass, exec_time)) print(" optimum: %s" % best) r = sad.greedy(obj, max_mass, sad.best_price) print(" best price: %s / %.1f%%" % (r, 100. * (best - r) / best)) r = sad.greedy(obj, max_mass, sad.worst_mass) print(" worst mass: %s / %.1f%%" % (r, 100. * (best - r) / best)) r = sad.greedy(obj, max_mass, sad.best_ratio) print(" best ratio: %s / %.1f%%" % (r, 100. * (best - r) / best))
def test_coursera_cases(self): test_cases_path = 'greedy_algorithms_mst_dynamic_programming/week4/test_cases' test__files = get_test_inputs(test_cases_path) for test_input in test__files: print("Testing " + test_input) test_case = read_items(test_input, sep=" ") expected = read_output(test_input) final_answer = knapsack(test_case[0], test_case[1]) self.assertEqual(expected, final_answer) print("Test OK")
def knap_func(): par1 = request.args.get('par1') #print(par1) par2 = request.args.get('par2') par3 = int(request.args.get('par3')) #print(par2) res = kp.knapsack(par1, par2, par3) res2 = np.array(res) print(res) return json.dumps(res2.tolist())
def knapsack_from_tracks(tracks, duration): shuffle(tracks) lengths = [item['track']['duration_ms'] / 1000 for item in tracks] tracks_to_play = [] if sum(lengths) <= int(duration): # Trivial case tracks_to_play = tracks else: indices_to_play = knapsack(lengths, lengths, len(lengths), int(duration)) tracks_to_play = [tracks[i] for i in indices_to_play] play_length = sum(lengths[i] for i in indices_to_play) print "target: %s\nachieved: %s\n" % (duration, play_length) shuffle(tracks_to_play) return jsonify(tracklist=tracks_to_play)
def resolve_collisions(to_cash, ways, cashes, videos): for key in to_cash: cash = cashes[key] if len(to_cash[key]) == 1: if cash.capacity >= videos[to_cash[key][0][1]].size: video = videos[to_cash[key][0][1]] cash.capacity -= video.size cash.put_video(video.id) if to_cash[key][0] in ways: del ways[to_cash[key][0]] else: to_cash[key] = [] update_to_cash(to_cash, ways) elif len(to_cash[key]) > 1: video_put = to_cash[key] num_videos = len(videos) data = {i: [0, videos[i].size, i] for i in range(num_videos)} for i in range(num_videos): data[i][0] += sum([el[0] for el in video_put if el[1] == i]) values = list(data.values()) values = [el for el in values if el[0]] total_value, result_items = knapsack(values, cash.capacity) sizes = [videos[el].size for el in result_items] for el, size in zip(result_items, sizes): cash.capacity -= size cash.put_video(el) new_video_put = [] for el in video_put: if el[1] not in result_items: new_video_put.append(el) to_cash[key] = new_video_put if not result_items: ways = {} ways2 = copy.deepcopy(ways) for el in ways2: if el[1] in result_items or len(ways[el]) == 1: del ways[el] else: ways[el].pop(0) return to_cash, ways
def solve_it(input_data): sack=knapsack.knapsack() # parse the input lines = input_data.split('\n') firstLine = lines[0].split() sack.n = int(firstLine[0]) sack.K = int(firstLine[1]) sack.w = np.zeros(sack.n) sack.x = np.zeros(sack.n) sack.v = np.zeros(sack.n) for i in np.arange(sack.n): line=lines[i+1].split() sack.v[i],sack.w[i]=float(line[0]),float(line[1]) sack.gurobi_solve() return sack.output_sol()
def solve_it(input_data): sack = knapsack.knapsack() # parse the input lines = input_data.split('\n') firstLine = lines[0].split() sack.n = int(firstLine[0]) sack.K = int(firstLine[1]) sack.w = np.zeros(sack.n) sack.x = np.zeros(sack.n) sack.v = np.zeros(sack.n) for i in np.arange(sack.n): line = lines[i + 1].split() sack.v[i], sack.w[i] = float(line[0]), float(line[1]) sack.gurobi_solve() return sack.output_sol()
def get_chip_knapsack(amount, choices, recursive=True): obtained_chips = [] done = False while not done: # get possible candidate denominations values = [pick for pick in sorted(choices) if pick <= amount] if len(values) > 7 and amount < sorted(choices)[-2]: values.pop() # [1] * len(values) = weight of each denomination in values list _, results_list = knapsack(values, [1]*len(values)).solve(amount) results = [values[num] for num in results_list] if amount: obtained_chips.extend(results) amount -= sum(results) if not recursive: done = True else: done = True return obtained_chips
def get_optimal_subset(self, max_num_words, ret_as=None): """ :param max_num_words: :param ret_as: either None, "str", or "str_list". which will return list of type sentence, single string, or list of string respectively. :return: """ weights = [s.weight for s in self.__sentences] values = [s.value for s in self.__sentences] opt_val, opt_subset = knapsack(weights, values, max_num_words) if ret_as == "str": sentences = "\n".join( [self.__sentences[i].text for i in opt_subset]) elif ret_as == "list_str": sentences = [self.__sentences[i].text for i in opt_subset] else: sentences = [self.__sentences[i] for i in opt_subset] return opt_val, sentences
def knapSacking(): #Creating neccessary variables #The loan amount borrowers request weight = [] #Simple interest amount after the loan amount gives using the formula value = [] #The loan constraint the maximum amount to borrow capacity = listOfConstraints[0] for borrower in finalLoanRequest: #Extracting borrower key #Using borrower key to find loan request #Using the loan request to find loan amount #Appends that value into weight weight.append(borrowerDict[borrower[0]][borrower[1]][0]) #Appends amount after simple interest of the above weight amount performed on the loan request0 value.append(borrower[2]) print("Knapsack solution returns:") global kArray #Perform knapsack kArray = knapsack.knapsack(weight, value).solve(capacity)
def knapsack_of_capturable_planets(universe, planet, distance): '''Returns the set of planets which can currently be captured which have the the most growth in `distance` turns''' candidates = [p for p in universe.not_my_planets if (planet.distance(p) < distance) and (p.turns_till_profit < TURNS_TO_PROFIT_MAX)] #log.error("distance: %s, LIST: %s " % (distance, candidates)) table = [] for c in candidates: nearest_enemy_planet = c.find_nearest_neighbor(owner=player.ENEMIES) #log.info("distance to enemy: %s " % (nearest_enemy_planet.distance(c))) #log.info("planet.turns_till_profit: %s " % (c.turns_till_profit)) #Check if planet will be caputured before our ships will get there future_planet = c.in_future(planet.distance(c)) #log.info("future_planet CANIDATE: %s " % (future_planet)) if future_planet.owner == player.ME: continue #Use the future state in case other fleets are in root cost = future_planet.ship_count+1 value = (distance - c.distance(planet)) * c.growth_rate table.append((c, cost, value)) return knapsack(table, planet.ship_count)
def test_non_greedy(): assert_equals(knapsack([(8, 8), (3, 5), (3, 5)], 8), [(3, 5), (3, 5)])
def test_larger_subset(): input_set = [(5, 10), (4, 40), (6, 30), (3, 50)] assert_equals(knapsack(input_set, 10), [(4, 40), (3, 50)])
def test_empty_items(): assert_equals(knapsack([], 5), [])
def test_only_include_once(): assert_equals(knapsack([(2, 2)], 4), [(2, 2)])
return True else: df = df[df.team != club] return False def player_string(index): player = df.loc[index] return ",".join([player.name, player.position, player.team]) while len(team) < TEAM_SIZE: # Convert points and cost to lists for knapsack algorithm points = list(df.points) cost = list(df.cost) cost = [int(10 * i) for i in cost] # Find best combination of players chosen = knapsack(points, cost, TEAM_SIZE - len(team), money * 10) chosen = df.iloc[chosen, :].sort("points", ascending=True) for player in chosen.iterrows(): index = player[0] if check_position(index) and check_club(index): add_player(index) else: break print(team.sort("points", ascending=False)) print("Cost: " + str(sum(team.cost))) print("Total points: " + str(sum(team.points)))
def testKnapsack3(self): self.assertEqual(hw.knapsack(5, [ [160, 4], [3, 25], [2, 1] ]), 26)
def test_1(self): v = [10, 40, 30, 50] w = [5, 4, 6, 3] capacity = 10 self.assertEqual(knapsack(w, v, capacity)[0], 150) self.assertEqual(knapsack(w, v, capacity)[1], [0, 0, 0, 3])
def main(): weights, values = parse(sys.argv[1]) weight_bound = int(prompt("Weight Bound")) items, score = knapsack(weights, values, weight_bound) print "The best score is %d and the items are %s" % (score, str(items))
def test_negative_value(): assert_equals(knapsack([(2, -3)], 2), [])
def test_zero_capacity(): assert_equals(knapsack([(1, 2), (2, 1)], 0), [])
def test_single_item_too_big(): assert_equals(knapsack([(2, 2)], 1), [])
def test_single_item_fits(): assert_equals(knapsack([(1, 1)], 1), [(1, 1)])
def testKnapsack4(self): self.assertEqual(hw.knapsack(7, [[3,10],[1,1],[4,10]]), 20)
def testKnapsack2(self): self.assertEqual(hw.knapsack(16, [[13,2],[2,6],[4,10]]), 16)
def testKnapsack1(self): self.assertEqual(hw.knapsack(40, [[13,50],[2,3],[25,13],[12,20]]), 73)
def test_decision(self): w = [3, 8, 5] v = [4, 6, 5] capacity = 8 self.assertEqual(knapsack(w, v, capacity)[1], [1, 0, 1])
def test_value_greater_than_size(): assert_equals(knapsack([(2, 5)], 3), [(2, 5)])
def test_value(self): w = [3, 8, 5] v = [4, 6, 5] capacity = 8 self.assertEqual(knapsack(w, v, capacity)[0], 9)
def test_too_small_capacity(): assert_equals(knapsack([(2, 3)], 1), [])
def test_best_of_two_choices(): assert_equals(knapsack([(2, 1), (2, 2)], 2), [(2, 2)])
def test_duplicate_item(): assert_equals(knapsack([(1, 1), (1, 1)], 1), [(1, 1)])
def test_size_greater_than_value(): assert_equals(knapsack([(5, 2)], 7), [(5, 2)])
import knapsackWithRepetition import knapsack print "Example from slides:" print "With repetition:" print knapsackWithRepetition.knapsack(10, [8, 6, 3], [20, 15, 8]) print "Without repetition:" print knapsack.knapsack(10, [8, 6, 3], [20, 15, 8]) #print knapsack(100, [8, 6, 3], [20, 15, 8]) print "Example from textbook:" print "With repetition:" print knapsackWithRepetition.knapsack(10, [6, 3, 4, 2], [30, 14, 16, 9]) print "Without repetition:" print knapsack.knapsack(10, [6, 3, 4, 2], [30, 14, 16, 9]) #print knapsack(100, [6, 3, 4, 2], [30, 14, 16, 9])