Localization in 2D world
<p>I am struggling with the following code for the localization of robot on 2D world of red and green grid cells. I am basically getting the error which states that list index out of range.</p>

<p><a href="https://i.stack.imgur.com/vZfh9.png" rel="nofollow"><img src="https://i.stack.imgur.com/vZfh9.png" alt="enter image description here"></a></p>

<pre><code>p=[.2,.2,.2,.2,.2]# Initial cell probability
w=[['R','G','G','R','R'],
   ['R','R','G','R','R'],
   ['R','R','G','G','R'],
   ['R','R','R','R','R']]# World
meas = ['G','G','G','G','G']   # measurements
mov  = [[0,0],[0,1],[1,0],[1,0],[0,1]]               # motion
phit = .6                      # Probability to measure: R-&gt;0.6
pmiss = .2                     # Probability to measure: R-&gt;0.2
pExact = .8                    # Prob. exact motion
pOver = .1                     # Prob. overshoot
pUnder = .1                    # Prob. undershoot

def entropy (p):
    s = [p[i]*log(p[i]) for i in range(len(p))]
    return round(-sum(s), 2)

def sense(p, z):
    q = []
    for i in range(len(p)):
        hit = w[i]==z
        q.append( p[i]*(phit*hit + pmiss*(1-hit)) )
    s = sum(q)
    q = [i/s for i in q]
    return q

#Moving u cells
def move(p, u):
    q = []
    for i in range(len(p)):
        motion = pExact * p[(i-u)%len(p)]
        motion += pOver * p[(i-u-1)%len(p)]
        motion += pUnder * p[(i-u+1)%len(p)]
        q.append(motion)
    return q

for i in range(len(meas)):
    p = sense(p, meas[i])
    r = [format(j,'.3f') for j in p]
    print "Sense %i:"%(i),
    print r, entropy(p)
    p = move(p, mov[i])
    r = [format(j,'.3f') for j in p]
    print "Move  %i:"%(i),
    print r, entropy(p)
    print
</code></pre>

<p>In routine sense() your program tries to access the 5th element of list <strong>w</strong> (index 4 in the list), unfortunately <strong>w</strong> only has 4 elements (only indices 0, 1, 2, 3 are valid)</p>

<p><strong>range(len(p))</strong> returns [0, 1, 2, 3, 4]</p>

<p>Also <strong>w[i]==z</strong> will never be true: indeed <strong>w[i]</strong> is a list of characters, <strong>z</strong> is a single character</p>

<p>sense() is probably not doing what you intended to originally.</p>

python grid cells