I do not understand this block of Python code. Boolean multiplication with a float?

I do not understand the q.append(p[i] * (hit * pHit + (1-hit) * pMiss)) line q.append(p[i] * (hit * pHit + (1-hit) * pMiss)) because the hit variable is a boolean. This boolean comes from hit = (Z == world[i]) What happens there? I only have a basic understanding of Python ... Still studying its constructs.

 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) 
+4
source share
3 answers

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

 p[i] * (pHit if hit else pMiss) 
+1
source

In arithmetic, Booleans are treated as integers. True considered as 1 , and False considered as 0 .

 >>> True + 1 2 >>> False * 20 0 >>> True * 20 20 
+8
source

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?

+5
source

Source: https://habr.com/ru/post/1445338/


All Articles