<p>下面是我如何解决这个问题的。<br/>
我们定义一个变量<code>can_lie</code>。它告诉你电脑是否被允许撒谎,如果他最后说的是事实,那就是<code>True</code>
然后如果我们被允许撒谎,并且只有一次超过两次,我们就撒谎了。<br/>
在此之后,我们不允许在下一轮中这样做,因此<code>can_lie</code>变成<code>False</code>。<br/>
然后我们会说与我们应该说的相反的话,因为我们在撒谎。<br/>
如果我们说的是真话,那么<code>can_lie</code>就变成了<code>True</code>,所以我们可以在下一轮中说出我们想说的任何话。<br/>
然后我们说出我们应该说的话</p>
<pre class="lang-py prettyprint-override"><code>
import random
myName = input('What is your name?~ ')
print('Well, ' + myName + '! I am thinking of a number from 1 to 100')
number = random.randint(1, 100)
guessesTaken = 0
result = ['low', 'high']
can_lie = True
while guessesTaken < 20:
guess = int(input(str(guessesTaken + 1) + '-Take a guess!~ '))
guessesTaken += 1
if can_lie and random.choice((True, False)):
#Here we lie
can_lie = False
if guess > number:
print('Your guess is too low !')
if guess < number:
print('Your guess is too high !')
else:
can_lie = True
if guess < number:
print('Your guess is too low !')
if guess > number:
print('Your guess is too high !')
if guess == number:
break
if guess == number:
print('Good job, ' + myName + '! You guess my number in ' + str(guessesTaken) + ' guesses')
else:
print('Nope! The number I was thinking of was ' + str(number))
</code></pre>
<p>此代码是随机的,但不会连续出现两次</p>