function [] = knapsack(p, W, c) | p = p)'; w = w(:)'; n = length(); n % # of x %% LP relaxation and round down value [x1
Posted: Mon May 09, 2022 6:26 am
hello, can anybody translate this matlab code into python language? your share of knowledge would be highly appreciated. Thanks a lot.. Its urgent for my midterm presentation.
function [] = knapsack(p, W, c) | p = p)'; w = w(:)'; n = length(); n % # of x %% LP relaxation and round down value [x1, cost_relaxation] = linprog (-p,w,c,[],[],zeros(n,1), ones(n,1)); cost_relaxation = -cost_relaxation; cost_rounddown = floor(cost_relaxation); %% intlinprog intcon = 1:n; [x2, cost_intlin] = intlinprog(-p, intcon,w,c,[],[],zeros(n,1), ones(n,1)); n; cost_intlin = -cost_intlin;
Base %% Sorting efficiency = p./w; x_iter = 1:n; temp = 0; for i = n-1
1 for j = 1:1 if efficiency(1) { efficiency (1+1) efficiency = swap(efficiency, i, temp); p = swap(p, j, temp): W = swap (w, j, temp); x_iter swap(x_iter, j, temp); end end end
function [x] = swap(x, i, temp) temp x(); x(i) = x(+1); x(+1) = temp; end
%% Dynamic programing X_sol = zeros(n,1,C+1, n+1); z = zeros(C+1, n+1); for j = 2:n+1 for d 1:w(1-1) z(d,i) = z(d, j-1); x_sol(:,1,d,j) = x_sol(:,1,d,j-1); end for d = w(1-1)+1:C+1 if z(d-w(1-1),j-1) + P(-1) > z(d, j-1) 1 p z(d,j) = z(d-w(-1),-1) + p(-1); x_sol(:,1,d,j) = x_sol(:,1, d-w(1-1),j-1); x_sol(1-1,1,d,j) = 1; else z(d,i) = z(d, j-1); X_sol(:,1,d,j) = x_sol(:,1,d,j-1); end end end x_real = zeros(n,1); for i = 1:n if x_sol(i,1,C+1, n+1) == 1 x_real(x_iter(i)) = 1; end end
function [] = knapsack(p, W, c) | p = p)'; w = w(:)'; n = length(); n % # of x %% LP relaxation and round down value [x1, cost_relaxation] = linprog (-p,w,c,[],[],zeros(n,1), ones(n,1)); cost_relaxation = -cost_relaxation; cost_rounddown = floor(cost_relaxation); %% intlinprog intcon = 1:n; [x2, cost_intlin] = intlinprog(-p, intcon,w,c,[],[],zeros(n,1), ones(n,1)); n; cost_intlin = -cost_intlin;
Base %% Sorting efficiency = p./w; x_iter = 1:n; temp = 0; for i = n-1
function [x] = swap(x, i, temp) temp x(); x(i) = x(+1); x(+1) = temp; end
%% Dynamic programing X_sol = zeros(n,1,C+1, n+1); z = zeros(C+1, n+1); for j = 2:n+1 for d 1:w(1-1) z(d,i) = z(d, j-1); x_sol(:,1,d,j) = x_sol(:,1,d,j-1); end for d = w(1-1)+1:C+1 if z(d-w(1-1),j-1) + P(-1) > z(d, j-1) 1 p z(d,j) = z(d-w(-1),-1) + p(-1); x_sol(:,1,d,j) = x_sol(:,1, d-w(1-1),j-1); x_sol(1-1,1,d,j) = 1; else z(d,i) = z(d, j-1); X_sol(:,1,d,j) = x_sol(:,1,d,j-1); end end end x_real = zeros(n,1); for i = 1:n if x_sol(i,1,C+1, n+1) == 1 x_real(x_iter(i)) = 1; end end