目录:一.题目及分析
二.代码块
1:题目以及对应的分析
在某班班委成员的选举中,已知王小红、李强、丁金生三位同学被选进了班委会。该班的甲,乙,丙三名学生预言如下:
甲说:王小红为班长,李强为生活委员。
乙说:丁金生为班长,王小红为生活委员。
丙说:李强为班长,王小红为学习委员。
班委会分工名单公布后发现,甲,乙,丙三人恰好都猜对了一半。问:王小红,李强,丁金生各任何职?
解:p :王小红为班长
q:李强为生活委员
r :丁金生为班长
s:王小红为生活委员
t:李强为班长
m:王小红为学习委员
用“1”表示命题正确,“0”表示命题错误
2:代码实现
ls = [0,1]
for p in ls:
for q in ls:
for r in ls:
for s in ls:
for t in ls:
for m in ls:
if (p==1 and r==1):#表示两者不可能同时成立,当出现此情况则终止循环,下同
continue
if (p==1 and s==1):
continue
if (p==1 and m==1):
continue
if (q==1 and s==1):
continue
if (q==1 and t==1):
continue
if (p==1 and t==1):
continue
A = (p and (not q)) or ((not p) and q)#甲说的一半对
B = (r and (not s)) or ((not s) and r)#乙说的一半对
C = (t and (not m)) or ((not t) and m)#丙说的一半对
F = A and B and C#三者同时成立
if F == 1:
print("%d,%d,%d,%d,%d,%d"%(p,q,r,s,t,m))
运行结果:
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 18:46:30) [MSC v.1929 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
=== RESTART: C:/Users/ASUS/AppData/Local/Programs/Python/Python310-32/班委竞选.py ==
0,1,1,0,0,1
根据结果可得:p==0 and q==1
r==1 and s==0
t==0 and m==1
即李强为生活委员,丁金生为班长,王小红为学习委员