Python中使用二进制搜索的猜谜游戏

2024-04-18 04:16:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用十个问题来猜一个日期。我可以让代码只问十个问题,但我很难找到正确的日期。程序一直运行到12月31日,我需要它来猜测用户正在思考的日期。我的输出有问题。我对编程还是个新手,所以任何帮助都会很棒。在

#Guess the Date
#Instructions for program
print ('Think of a specific date in any year')
print ('e.g., Jan 1 or Feb 29 or Jul 4 or Dec 25')
print ('Truthfully answer "Yes" or "No" to the following questions')
print ('I will determine the date in ten questions or less')

#Return a list of elements, each element is a date in a calendar year
def Calendar(monthNames, numDaysInMonth): #defining Calendar

    if len(monthNames) != len(numDaysInMonth): 
        return []

    dates = []
    idx = 0     #index is set to zero

    while idx < len(monthNames):
        for date in range(1, numDaysInMonth[idx] + 1):
            dates.append(monthNames[idx] + " " + str(date))
        idx = idx + 1
    return dates
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]   #list of months
numDaysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] #list of how many days in each month

#This is a binary search
first =Calendar(monthNames,numDaysInMonth) #first defined through the Calendar code block

def guess_game(first = Calendar(monthNames,numDaysInMonth)): #defining guess_game using months list and numDays item in the Calendar code to work the search

    if len(first) == 1:
        return first[0]

    mid = len(first)//2

    if is_earlier(first[mid]):    #list mindpoint
        return guess_game(first[:mid])
    else:
        return guess_game(first[mid:])

#Answer output, what is out putted in the python shell
def is_earlier(guess = 10): #defining is_ealier and setting the number of guesses equal to 10


    answer = input("Is {} earlier then your date? (Yes - earlier /No - not earlier) ".format(guess))#10 or less guesses to to find answer

    if answer.upper() == "Yes": #if true user can put No, no, n
        return True

    else:
        return False #if false user can put Yes, yes, y

guess_game() #intialize quess_game

Tags: orthetoingamedatereturnif
2条回答

错误出现在以下行:

if answer.upper() == "Yes":

即使用户输入Yes,它也会被str.upper转换成{},因此{}永远不会运行。在

此外,如果程序能正确地猜出你的日期呢?你不能给用户选择的选项。您可以通过让用户输入1、2或3来更改此设置,以表示更早、更多或相等。在

而且,你已经颠倒了二进制搜索的逻辑。如果日期早于您的猜测,则丢弃后半部分,反之亦然。在


^{pr2}$

其中一个问题是代码的这一部分:

if answer.upper() == "Yes": #if true user can put No, no, n
   ^^^^^^^^^^^^^^^^^^^^^^^

answer.upper()会将'yes'变成{},而不是{}。平等从来都不是真的,所以你给出的每一个答案都会被解释为“不”。以下方法可行:

^{pr2}$

另一个问题是您选择放弃哪一半搜索空间的逻辑:

if is_earlier(first[mid]):    #list mindpoint
    return guess_game(first[:mid])
else:
    return guess_game(first[mid:])

如果中点早于日期,则需要继续搜索晚于日期的一半,而不是更早的那一半。在

相关问题 更多 >