Overview : I am a novice in python and am implementing a Localization algorithm in python. The robot executing this code first senses its environment and and multiplies the probability distribution by sensor_right if the color of the cell matches the color in the measurements list. The move function moves the robot to the desired location with a 0.8 probability of a successful movement:
Code :
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 =1
p_move = 0.8
def show(p):
for i in range(len(p)):
print p[i]
p = []
sum=0
for i in range(len(colors)):
for j in range(len(colors[i])):
sum+=1
p=[[1.0/sum for j in range(len(colors[i]))] for i in range(len(colors))]
def sense(p,z):
q=[]
sum=0
for i in range(len(colors)):
new=[]
for j in range(len(colors[i])):
if (colors[i][j]==z) :
new.append(p[i][j]*sensor_right)
sum+=p[i][j]*sensor_right
else :
new.append(p[i][j]*(1-sensor_right))
sum+=p[i][j]*(1-sensor_right)
q.append(new)
for i in range(len(q)):
for j in range(len(q)):
q[i][j]/=sum
return q
def move(lst,u=[]):
q=[]
if (u[0]!=0) :
for i in range(len(lst)):
new=[]
for j in range(len(lst[i])):
val=lst[j-u[0]][i]*p_move
new.append(val)
q.append(new)
elif (u[1]!=0) :
for i in range(len(lst)):
new=[]
for j in range(len(lst[i])):
val=lst[i][j-u[1]]*p_move
new.append(val)
q.append(new)
return q
for i in range(len(measurements)):
p=sense(p,measurements[i])
p=move(p,motions[i])
show(p)
Problem : The compiler returns the following ouput :
in sense
new.append(p[i][j]*(1-sensor_right))
IndexError: list index out of range
When I called commented the motions method, the compiler didn't throw the error and showed the correct output . Oddly though, when I checked the output of the motions method, the 2 d list returned by it had the same dimensions as the 2-d list passed to the sense method when it is called in the loop.Also, why didn't the compiler throw the error at
new.append(p[i][j]*sensor_right)
sum+=p[i][j]*sensor_right
if the index was out of range.
Why is the compiler throwing this error?