Skillfully use python to solve logic problems, very simple!

Before going to bed last night, I read a copy of "600 Thinking Training for Harvard Students" that I bought in junior high school, and found that some problems can be solved with a computer, so I got up early and knocked it casually.

The first question: 122 Guess the name

img

Core idea: traverse all the names, and assume that they are the names written by the teacher, and then put them into the situation where the students are talking to see if it satisfies the situation where only one person is right.

#122代码
list=['a','b','c','d']
for x in list:
    if (int(x=='c')+int(x!='b')+int(x!='c')+int(x=='a')==1):
        print(x)
#122运行结果>>b

The final answer is 'b', which is the classmate B in the question.

Look at the 126 and 127 marriage questions again

img

img

img

126 is the same as 122 just now, it is very simple, just express it, but 127 has changed a little, and it can be made through simple logic.

#126代码
list=['a','b','c']
for x in list:
    if (int(x != 'a') + int(x == 'a') + int(x != 'c')  == 1):
        print(x)
#126运行结果>>c

The final answer is 'c', which is the lead box in the question.

127 There is at least one true, then the number of true is greater than or equal to 1, and at least one is false, that is, the number of logical negations of the original statement is greater than or equal to 1. It can be expressed in python.

#127代码
list=['a','b','c']
for x in list:
    if ( (int(x != 'b') + int(x != 'b') + int(x == 'c')  >= 1) and int(x == 'b') + int(x == 'b') + int(x != 'c')>=1):
        print(x)
#127运行结果>>a

The final answer is 'a', which is the golden box in the question.

Question 3: 155 Who is the perpetrator

img

There are three people who lie, that is, the true number is 1.

#155代码
list=['a','b','c','d']
for x in list:
    if (int(x == 'b') + int(x == 'd') + int(x != 'c')  + int(x != 'd')== 1):
        print(x)
        
#155运行代码>>c

The final answer is 'c', which is the C in the question.

One last question, if you are interested, give it a try!

img

Guess you like

Origin blog.csdn.net/Dai_sir_man/article/details/120074513