📜  使用二进制搜索的Python的数字猜谜游戏

📅  最后修改于: 2021-05-04 08:55:22             🧑  作者: Mango

在猜数字游戏中,用户在定义的范围内选择一个数字,然后程序猜数字。如果猜出的数字是错误的,则用户告诉程序实际数字是否大于猜想的数字。同样,程序将再次猜测该数字,直到未猜测到实际数字为止。

方法:想法是使用二进制搜索,其中每一步都减少了一半的搜索空间。下面是该方法的说明:

  • 初始化数字猜测的开始和结束范围。
  • 猜数字在搜索空间的中间。那是

    Number  = \frac{startRange + endRange}{2}

  • 如果猜中的数字正确,则终止程序。
  • 否则,询问用户猜测的数字是否小于猜测的数字。如果是,则相应地减少搜索空间。

下面是上述方法的实现:

Python
# Python implementation for the 
# number guessing using 
# Binary Search
  
# Global Arguments for playing game
args = ["N", "N", "Y"]
index = -1
  
# Temporary function for taking
# input from the local arguments list
def input():
    global index, args;
    index += 1
    return args[index]
  
# Function to guess the number in 
# a defined range of the number
def guessNumber(startRange, endRange):
    if startRange > endRange:
        return True
      
    # Middle of the range
    mid = (startRange + endRange)//2
      
    # Asking user about the 
    # actual number
    print("Is the number is ",
        mid, "?", end = " ")
    user = input()
    print(user)
      
    # Condition to check if the 
    # guessed number is actual number
    if user == "Y" or user == "y":
        print("Voila ! Successfully Guessed Number.")
        return False
          
    # Condition to check if the 
    # guessed number is not correct
    elif user == "N" or user == "n":
        print("Actual number is greater than",\
                        mid, "?", end = " ")
        user = input()
        print(user)
        if user == "Y" or user == "y":
            return guessNumber(mid+1, endRange)
        elif user == "N" or user == "n":
            return guessNumber(startRange, mid-1)
        else:
            print("Invalid Input. Print 'Y'/'N'")
            return guessNumber(startRange, endRange)
      
    # Condition to check if the user
    # input was invalid 
    else:
        print("Invalid Input. Print 'Y'/'N' ")
        return guessNumber(startRange, endRange)
  
# Driver Code
if __name__ == "__main__":
    print("Number Guessing game in python")
    startRange = 1
    endRange = 10
    print("Guess a number in range (1 to 10)")
      
    out = guessNumber(startRange, endRange)
      
    if out:
        print("Bad Choices")


输入:
N
N
Y
输出:
Number Guessing game in python
Guess a number in range (1 to 10)
Is the number is  5 ? N
Actual number is greater than 5 ? N
Is the number is  2 ? Y
Voila ! Successfully Guessed Number.