version: python 3
The code is straight forward
dp = [[float('inf')] * 3] * 3
dp[0][0] = 1
what I get
- [[1, inf, inf], [1, inf, inf], [1, inf, inf]]
what I expect to get
- [[1, inf, inf], [inf, inf, inf], [inf, inf, inf]]
Any clues ?
list * number
means not a copy of the list but number
references to the same list (same memory location). That's why mutating one of the three lists will mutate also the other ones.
A solution could be (create the lists using a loop):
dp = [[float("inf")] * 3 for i in range(3)]