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

时间:2017-08-06 03:12:57

标签: python

我想在10个问题中猜测一个日期。我可以让代码只询问十个问题,但是我无法找到正确的日期。该程序一直持续到Decemeber 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

2 个答案:

答案 0 :(得分:1)

这部分代码存在一个问题:

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

answer.upper()会将'yes'变为'YES',而非'Yes'。平等永远不会成立,所以你给出的每一个答案都会被解释为“不”。以下方法可行:

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

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

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

如果中点早于您的日期,您希望继续搜索较晚的一半,而不是更早。

答案 1 :(得分:1)

错误在于这一行:

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

即使用户输入Yes,也会YES转换为str.upper,因此永远不会运行if

此外,如果程序设法正确猜测您的日期怎么办?您没有为用户提供选择该选项的选项。您可以通过让用户输入1,2或3来更改此值,包括更早,更多或相等。

此外,您已经颠倒了二元搜索的逻辑。如果日期早于您的猜测,则丢弃后半部分,反之亦然。

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

#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

#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
    mid = len(first)//2

    val = is_earlier(first[mid])

    if val == 1:    #list mindpoint
        return guess_game(first[mid - 1:])
    elif val == 2:
        return guess_game(first[:mid + 1])
    else:
        return 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
    return int(input("{}: 1 - earlier, 2 - later, 3 - equal?: ".format(guess))) #10 or less guesses to to find answer

if __name__ == '__main__':
    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')

    print(guess_game()) #intialize guess_game