I'm getting list index out of range even though I've kept a condition so that it would not check such a state where the index is not inside the limit specified. Please go through the code below.
T=int(input())
c=1;
f=0;
d=[]
for i in range(T):
a=int(input())
A=list(map(int, input().strip().split()))
b=int(input())
B=list(map(int, input().strip().split()))
for j in range(a-1):
for k in range(b):
if(A[j] == B[k]):
if(j+c < a, k+c< b):
while(f==0):
if(j+c < a, k+c < b):
c += 1
if(A[j+c]==B[k+c]):
f=1
if(f==0):
d.append(c)
f=0;
c=1;
d.sort;
d= []
print (d[-1])
This is the error that I get:
Runtime Error:
Runtime ErrorTraceback (most recent call last):
File "/home/a065c7cd2e000ec65fe6b148ca7dee08.py", line 17, in <module>
if(A[j+c]==B[k+c]):
IndexError: list index out of range
I was trying to solve the question of Longest Common Increasing Subsequence. It would be helpful if the correct for it would be provided otherwise. :)
Given two arrays, find length of the longest common increasing subsequence (LCIS). For example length of LCIS for A[] = {3, 4, 9, 1} and B[] = {5, 3, 8, 9, 10, 2, 1} is 2 ( The subsequence {3, 9} is the longest subsequence that is both common and increasing. As another example LCIS for A[] = {1, 1, 4, 3} and B[] = {1, 1, 3, 4} is 2 (There are two subsequences {1, 4} and {1, 3}).
First, the statement if(a, b):
is not the same as if(a and b):
, as if(a, b):
is checking whether the tuple (a, b)
is empty or not, and since it is not empty, it returns true no matter what. Try
if(False, False):
print('What?!')
and see that the print does execute.
For your question, within your code you have this:
if(j+c < a and k+c < b):
c += 1
if(A[j+c]==B[k+c]):
so, suppose that j+c
is 1 and a
is 2, we'd enter the block. Then, we add one to c
, so now j+c
is 2, and a
is 2, and then we'd check A[2]
which is out of bounds.
And as a side note, you can use the len function to get the length of a list. So your input could look like:
A=list(map(int, input('A:').strip().split()))
B=list(map(int, input('B:').strip().split()))
a, b = len(A), len(B)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.