I am doing Project Euler Problem 15. I used the right algorithm, but it didn’t seem to work. Here’s my code:
f = [[0] * 21] * 21
# init the list
for i in range(21):
f[0][i] = 1
f[i][0] = 1
for i in range(21):
for j in range(21):
f[i][j] = f[i-1][j] + f[i][j-1]
print f[20][20]
when I finished initializing the list, I printed it. I expected it like [[1, 1, 1...], [1, 0, 0...]...], but it turned [[1, 1, 1...], [1, 1, 1...]...] and I can’t figure why.
I used to use C-like language and I thought the list in Python is kind of like the array in C, so I used them in the same way.
When multiplying a list, you are not creating separate lists but rather create multiple references to the same list.
Instead, do this:
You can see the difference when using the
id()function:Separate objects have separate memory id values, while your lists have the same result for each
id()call, showing they are all the same list.