在猜数游戏中,用户在定义的范围内选择一个数字,然后程序猜出这个数字。如果猜测的数字是错误的,则用户告诉程序实际数字是否大于猜测的数字。同样,程序再次猜测数字,直到猜不出实际数字为止。
方法:想法是使用二分搜索,其中在每一步中搜索空间的一半减少。下面是该方法的说明:
- 初始化猜数的开始和结束范围。
- 猜测数字作为搜索空间的中间。那是
- 如果猜测的数字是正确的,则终止程序。
- 否则,询问用户猜测的数字是否小于猜测的数字。如果是,则相应地减少搜索空间。
下面是上述方法的实现:
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.
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。