Python numbers game reverse

后端 未结 4 1990
我在风中等你
我在风中等你 2021-01-29 13:07

So I have to make a \"game\" on python were I think of a number and it tries to guess the number. I have to tell it if it\'s higher or lower than the number it guessed and conti

4条回答
  •  后悔当初
    2021-01-29 13:20

    Its very similar to a Binary Search Algorithm

    Its just that the usual mid value in such algorithms can be replaced by randrange(Low,High)

    I'm not sure if this is a working code but I suggest you do it recursively:

    items= range(l,h)
    def random_search(ask, items, l, h):
        """
        Random search function.
        Assumes 'items' is a sorted list.
        The search range is [low, high)
        """
        ask = input("Is this number correct? y for yes or n for no.")
        lowOrHigh = input ("Is this number too high or low? h for high, l for low.")
        elem = randrange(l,h)
    
        if ask == 'y':
            return elem
        elif h == l:
            return False
        elif lowOrHigh == 'h':
            items= range(l,elem)
            return random_search(ask, items, l, elem)
        else:
            items= range(elem, h)
            return random_search(ask, items, elem, h)
    

提交回复
热议问题