| 1 | {{{#!python |
| 2 | # Ask the user to guess a number between 1 and 10 |
| 3 | |
| 4 | from random import randint, seed |
| 5 | |
| 6 | |
| 7 | def 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 | |
| 15 | def 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 | |
| 33 | seed(7789798) |
| 34 | h = randint(1, 10**9) |
| 35 | t = guess_hidden(1, 10**9, h) |
| 36 | print("The hidden number was guessed in " + str(t) + " tries.") |
| 37 | |
| 38 | }}} |