Please help to fix my code at TypeError: solve_knapsack() missing 3 required positional…
- User
Please help to fix my code at TypeError: solve_knapsack() missing 3 required positional arguments: 'c', 'weights', and 'values' -> #!/usr/bin/python3
from pwn import *
def get_values(test_n): print(f'Getting values for {test_n + 1} test') io.recvuntil(f'Test {test_n + 1}/100\n'.encode()) N = int(io.recvuntil(b' ').decode()) C = int(io.recvline().rstrip().decode()) weights = [] values = [] for _ in range(N): product = io.recvline().rstrip().decode().split(' ') weights.append(int(product[0])) values.append(int(product[1]))
codeprint(f'Testing values for {N}, {C}, {weights}, {values}') return N, C, weights, valuesKnapsack problem solver implementation
Below is a solver for the knapsack problem following the dynamic programming path. One can
either find a program online to do this, or write a solver himself
def solve_knapsack(n, c, weights, values): dp = [[0 for _ in range(c + 1)] for _ in range(n + 1)] for i in range(1, n + 1): for w in range(1, c + 1): if weights[i-1] <= w: dp[i][w] = max(dp[i-1][w], dp[i-1][w-weights[i-1]] + values[i-1]) else: dp[i][w] = dp[i-1][w] return dp[n][c]
def send_solution(max_sum): print(f'Sending solution {max_sum}') io.sendline(f'{max_sum}'.encode())
def get_flag(): io.recvuntil(b'HTB{') return b'HTB{' + io.recvline().rstrip()
def pwn(): for i in range(0, 99): send_solution(solve_knapsack(get_values(i))) get_flag()
if name == 'main': ip = '94.237.55.180' port = 53327 io = remote(ip, port) pwn()
- Assistant
The error message you're encountering is because the
solve_knapsackfunction is expecting four arguments (n,c,weights, andvalues), but it's being passed only a tuple returned fromget_values(i)in the call inside thepwn()function. To fix this, you'll need to unpack the tuple returned byget_values(i)and pass the unpacked values tosolve_knapsack.Here's the corrected
pwn()function:pythondef pwn(): for i in range(0, 99): n, c, weights, values = get_values(i) # Unpack the returned tuple max_sum = solve_knapsack(n, c, weights, values) # Pass unpacked values send_solution(max_sum) return get_flag() # Don't forget to actually return and use the flag