甲、乙、丙、丁四人的血型各不相同,甲说:“我是A型”。乙说:“我是O型”。丙说:“我是AB型”。丁说:“我不是AB型”。四个人中只有一个人的话是假的。
思路:四个人的血型肯定都在[“A”,“B”,“O”,“AB”]范围内,所以用for循环让四个人轮流等于这四种血型,然后再用判断语句,选出正确的组合方法; 稍微的难点就是如何写判断语句,判断语句讲解如下:
((J1 and Y1 and B1 and not D1) or (J1 and Y1 and not B1 and D1) or (J1 and not Y1 and B1 and D1) or (not J1 and Y1 and B1 and D1))==1
,这里的意思就是,四个人中三个为真话,一个为假话;(J!=Y and Y!=B and B!=D and D!=J and J!=B and Y!=J and Y!=D)
;将以上两个条件结合起来,就是最后的答案,代码如下:
ls = ["A","B","O","AB"]
for J in ls:
for Y in ls:
for B in ls:
for D in ls:
J1 = (J == "A")
Y1 = (Y == "O")
B1 = (B == "AB")
D1 = (D != "AB")
if(((J1 and Y1 and B1 and not D1) or (J1 and Y1 and not B1 and D1) or
(J1 and not Y1 and B1 and D1) or (not J1 and Y1 and B1 and D1))==1
and (J!=Y and Y!=B and B!=D and D!=J and J!=B and Y!=J and Y!=D)):
print( "甲是%s型血,乙是%s型血,丙是%s型血,丁是%s型血。" %(J, Y, B, D))