Changes between Initial Version and Version 1 of GuessANumber


Ignore:
Timestamp:
Nov 3, 2022, 10:45:57 AM (2 years ago)
Author:
monga
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • GuessANumber

    v1 v1  
     1{{{#!python
     2# Ask the user to guess a number between 1 and 10
     3
     4from random import randint, seed
     5
     6
     7def play(guess: int, hidden: int) -> str:
     8    if guess == hidden:
     9        return "ok"
     10    elif guess > hidden:
     11        return "smaller"
     12    else:
     13        return "bigger"
     14
     15def guess_hidden(min_g: int, max_g: int, hidden: int) -> int:
     16    """Return the number of tries to guess.
     17    """
     18    tries = 0
     19    result = ""
     20   
     21    while result != "ok":
     22        tries += 1
     23        mid = (max_g + min_g) // 2
     24        result = play(mid, hidden)
     25        if result == "ok":
     26            return tries
     27        if result == "smaller":
     28            max_g = mid
     29        else:
     30            min_g = mid
     31
     32
     33seed(7789798)
     34h = randint(1, 10**9)
     35t = guess_hidden(1, 10**9, h)
     36print("The hidden number was guessed in " + str(t) + " tries.")
     37
     38}}}