My knapsack code is giving wrong output?
<p>I was trying to write a simple 0-1 knapsack problem but am encountering some error. Help would be appreciated.</p>

<pre><code>T = int(input().strip())
def knapsack(n,k,ar):
    if n==0 or k==0:
        return 0
    elif ar[n-1]&gt;k:
        return knapsack(n-1,k,ar)
    else:
        return max(knapsack(n-1,k,ar),ar[n-1] + knapsack(n-1,k-ar[n-1],ar))
for t in range(T):
    a = input().strip()
    n,k = int(a[0]),int(a[2])
    ar = [int(i) for i in input().strip().split(' ')]
    print(knapsack(n,k,ar))
</code></pre>

<p>I ran this again an input of </p>

<pre><code>2
3 12
1 6 9
5 9
3 4 4 4 8
</code></pre>

<p>and I am receiving wrong output? I cannot find any error. Thanks in advance</p>

<p>Output</p>

<pre><code>1
8
</code></pre>

<p>Your algorithm is fine but your input to the function is wrong.  </p>

<p>In the first input, the line <code>n,k = int(a[0]),int(a[2])</code> is taking <code>3</code> and <code>1</code> as an input instead of <code>3</code> and <code>12</code>.<br>
I guess you should use <code>list(map(int, input().split()))</code> instead, and get <code>a[0]</code> and <code>a[1]</code>.</p>

python algorithm python-3.x knapsack-problem