假设我想到1到100之间的密码。
你被要求猜一个数字,我会回答"猜得更高"或者"猜得更低"或"纠正"。游戏一直持续到你猜对了。
我有兴趣创建用于以系统方式搜索此密码的算法。
例如, 蛮力---猜测1,2,3,4 ...... 100,直到我正确
我写作的原因是为了解决另一种技巧。我有兴趣猜测使用树形结构。例如,我的第一个猜测是50.我的第二个猜测是25或75.我的第三个猜测是13或37,如果我在最后一轮猜测25或我的第三个猜测是63或87如果我在最后一轮猜测75 。它基本上将数字线切割成较小的部分。
def guessByDividing(prevGuess, feedback, floor, ceil):
window = (ceil - floor)
if prevGuess == 100:
guess = int(prevGuess/2)
return [guess, floor, ceil]
if feedback == "guess higher":
floor = prevGuess
guess = int(prevGuess + (window / 2))
return [guess, floor, ceil]
elif feedback == "guess lower":
ceil = prevGuess
guess = int(prevGuess - (window / 2))
return [guess, floor, ceil]
def playDivideConquer():
guessList = []
gameOver = False
feedback = "guess lower"
guess = 100
floor = 1
ceil = 100
while not gameOver:
guess, floor, ceil = guessByDividing(guess, feedback, floor, ceil)
guessList.append(guess)
# Provide Clues
if guess > secretNumber:
print("Lower than " + str(guess) + "--- Number of guesses = " + str(len(guessList)))
feedback = "guess lower"
elif guess < secretNumber:
print("Higher than " + str(guess) + "--- Number of guesses = " + str(len(guessList)))
feedback = "guess higher"
else:
print("CORRECT --- The secret number is " + str(secretNumber))
gameOver = True
print(guessList)
它无法正常工作,我不确定如何解决这个问题。有人可以帮忙吗?我也对其他快速查找密码的策略感兴趣。
谢谢
答案 0 :(得分:0)
好吧,我还无法弄清楚你的代码有什么问题。但是从这个问题来看,我想这就是你正在寻找的东西
# This is a guess the number game.
import random
guessesTaken = 0
number = random.randint(1, 101)
print('I am thinking of a number between 1 and 100.')
while guessesTaken < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
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:
guessesTaken = str(guessesTaken)
print('Good job! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)