Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursion error for a algorithmic problem

I was trying to do the question- First negative integer in every windows of size k from a array (b) of size n.
I tried using recursion but the below error came. I am trying to figure out but didn’t get my mistake. Please look into the code below

ans = []
def fnc(b,n,k):
    global ans
    dq = []
    
    for i in range(0,k):
        if b[i]<0:
            dq.append(b[i])
    if len(dq) != 0:
        ans.append(dq[0])
    else:
        ans.append(0)
        
    dq = []
    b.remove(b[0])
    bnew = b
    nnew = len(bnew)  # or nnew = n-1
    
    while len(bnew) > 1:
        fnc(bnew,nnew,k)

input:
B = [12, -1, -7, 8, -15, 30, 16, 28]
N = 8
K = 3
fnc( B, N, K)
print(ans)

Showing error List Index out of range

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you are recursively removing the first element of B, so in the run you will encounter the state where len(b) < k, so I would recommend to change the while loop to :

while len(bnew) > k:
   fnc(bnew,nnew,k)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading