Reputation: 63
So I'm doing day 13 of advent of code and ran into this problem and can't seem to understand what's happening.
Here's my code:
road = open('day13t.txt').read().strip().split('\n')
ogroad = [ list(x) for x in road ]
for i,r in enumerate(ogroad):
for j,c in enumerate(r):
if c == '>' or c == '<':
ogroad[i][j] = '-'
if c == '^' or c == 'v':
ogroad[i][j] = '|'
rdict = {'-':'>', '\\':'v', '/':'^'}
ddict = {'|':'v', '\\':'>', '/':'<'}
ldict = {'-':'<', '\\':'^', '/':'v'}
udict = {'|':'^', '\\':'<', '/':'>'}
test = [ list(x) for x in road ]
nroad = [ list(x) for x in road ]
for i in range(3):
for i, l in enumerate(test):
for j, c in enumerate(l):
if c == '>':
ns = ogroad[i][j+1]
nroad[i][j+1] = rdict[ns]
if c == '<':
ns = ogroad[i][j-1]
nroad[i][j-1] = ldict[ns]
if c == 'v':
ns = ogroad[i+1][j]
nroad[i+1][j] = ddict[ns]
if c == '^':
ns = ogroad[i-1][j]
nroad[i-1][j] = udict[ns]
test = list(nroad)
nroad = list(ogroad)
xroad = [ ''.join(x) for x in ogroad ]
for l in xroad:
print(l)
So these lists seem to have taken on a life of their own because in the last few lines of the outermost for loop I print out the contents of xroad which is basically ogroad. And I don't even touch ogroad at all in the for loops but it gives a different output every iteration.
Input I use:
/->-\
| | /----\
| /-+--+-\ |
| | | | v |
\-+-/ \-|--/
\------/
Upvotes: 1
Views: 61
Reputation: 10969
list()
only creates a flat copy. This means lists in the list aren't copied but shared. Example in shell:
>>> t=[[42]]
>>> t2 = list(t)
>>> t is t2
False
>>> t[0] is t2[0]
True
>>> t2[0][0] = 43
>>> t
[[43]]
Upvotes: 3