I’ve been working on the code shown below for udacity. I’m trying to figure out why the lists ‘g’ and ‘p’ are acting as the same list when ‘g’ is created by calling list(p). When the print statement (print[i][j]) is called in the move function it shows that ‘p’ is being overwritten when ‘g’ is changed. I just started programming in python and I would appreciate any help. Thanks in advance.
colors = [['red', 'green', 'green', 'red' , 'red'],
['red', 'red', 'green', 'red', 'red'],
['red', 'red', 'green', 'green', 'red'],
['red', 'red', 'red', 'red', 'red']]
measurements = ['green', 'green', 'green' ,'green', 'green']
motions = [[0,0],[0,1],[1,0],[1,0],[0,1]]
sensor_right = 0.7
p_move = 0.8
def show(p):
for i in range(len(p)):
print p[i]
total = len(colors[0])*len(colors)
for i in range(len(colors)):
p.append([])
for j in range(len(colors[i])):
p[i].append(1./total)
print p
def move(g,c,r):
t = list(g)
for i in range(len(g)):
for j in range(len(g[i])):
print p[i][j]
t[i][j] = t[(i-c)%len(g)][(j-r)%len(g[i])] * p_move
print p[i][j]
s = sum_table(t)
for i in range(len(g)):
for j in range(len(list(g[i]))):
t[i][j] /= s
return t
def sum_table(g):
sum = 0
for i in range(len(g)):
for j in range(len(g[i])):
sum += g[i][j]
print sum
return sum
move(list(p),0,1)
print p
I haven’t followed through your code in detail, but the source of your trouble is likely the use of two dimensional data structures (lists of lists). In Python, the
list()constructor is a shallow copy, which only copies one level of list. You may be able to avoid the problem you’re seeing using thecopy.deepcopy()function where appropriate.One trick is to use
id(p)andid(g)to find out what the actual object identity is for each reference. This sort of debugging may help isolate your problem. You’re calling thelist()constructor a lot, probably much more than necessary. Creating unnecessary copies of data structures like this will make much more work for the CPU and can affect performance critical code.