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
CodePudding user response:
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)