8

I don't understand the line q.append(p[i] * (hit * pHit + (1-hit) * pMiss)), because the variable hit is a boolean value. That boolean value comes from hit = (Z == world[i])

What's going on there? I only have a basic understanding of Python...

p = [0.2, 0.2, 0.2, 0.2, 0.2]

world = ['green', 'red', 'red', 'green', 'green']
Z = 'red'
pHit = 0.6
pMiss = 0.2

def sense(p, Z):
    q=[]
    for i in range(len(p)):
        hit = (Z == world[i])
        q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
        s = sum(q)
        for i in range(len(p)):
            q[i]=q[i]/s      
    return q

print sense(p,Z)
Georgy
  • 12,464
  • 7
  • 65
  • 73
user836087
  • 2,271
  • 8
  • 23
  • 33

3 Answers3

17

In arithmetic, booleans are treated as integers. True is treated as 1 and False is treated as 0.

>>> True + 1
    2
>>> False * 20
    0
>>> True * 20
    20
Tim
  • 11,710
  • 4
  • 42
  • 43
14

In python, booleans are a subclass of int:

>>> isinstance(True, int)
True

They are basically 1 and 0:

>>> True * 1
1
>>> False * 1
0

See Why is bool a subclass of int?

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
6

True is 1 and False is 0, as others have answered. So basically, what it does (and what should've been written) is:

p[i] * (pHit if hit else pMiss)
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124