how to fix list index out of range error in this case?

96 views Asked by At

crossword vertical solve function, the program gives list index out of range in 'if crosswords[num]==None' sratement

that statement is provided to eliminate such error

def find_word_vertical(crosswords,word):
    word_list=[i for i in word]
    l=len(word_list)
    index=[]
    for col in range(len(crosswords[0])):
        for row in range(len(crosswords)):
            if word_list[0]==crosswords[row][col]:
                num=row
                ok=True
                for ch in range(l):
                    if crosswords[num]==None:
                        break
                        ok=False
                    else:
                        if word_list[ch]==crosswords[num][col]:
                            num+=1
                        else:
                            ok=False
                if ok:
                    return [row,col]
    return None

i can't find the mistake because the program runs for some example test case but the error shows up at an unknown test case. the exact test case does not appear on the screen because of 'out of index' error. Sample Question=find_word_vertical([['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']],'cat')

1

There are 1 answers

0
Pawan Ps On
if crosswords[num]==None:
    break
    k=False

this statement was wrong and the correct statement is:

if num>=len(crosswords):
    k=False
    break

if element doesn't exist in list it does not return None but rather an error.