egonSchiele / grokking_algorithms

Code for the book Grokking Algorithms (https://amzn.to/29rVyHf)
Other
11.73k stars 3.8k forks source link

modify index error #250

Open Case3y opened 1 year ago

Case3y commented 1 year ago

An error occurred in the indexing of the list(dp_table): IndexError: list assignment index out of range modify its index

TylerWelch commented 1 year ago

Instead of switching the variables, it cant degradate the index on the other side of the assignment it should be j-1 i-1 not i-1 i-1. That is not a index location.

Case3y commented 1 year ago

Instead of switching the variables, it cant degradate the index on the other side of the assignment it should be j-1 i-1 not i-1 i-1. That is not a index location.

yes, I forget it! I think the final correct code is as follows:

dp_table_blue = ["b", "l", "u", "e"]
dp_table_clues = ["c", "l", "u", "e", "s"]
dp_table = [[0 for i in range(len(dp_table_blue))] for i in range(len(dp_table_clues))]
print(dp_table)  

for i in range(0, len(dp_table_clues)):
    for j in range(0, len(dp_table_blue)):
        if dp_table_clues[i] == dp_table_blue[j]:
            dp_table[i][j] = dp_table[i - 1][j - 1] + 1
        else:
            dp_table[i][j] = 0

print(dp_table)