@simontiger/

BinaryNumGuessingGame

Python

Think of a number 1-100. The program will use Binary Search to guess it within 7 takes!

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import math, random

def start_game(maximum):
  def ask_comparison(num):
    return input("Is it " + str(num) + "? (</=/>): ")
  
  print("")
  binary_search(ask_comparison, 0, maximum)

def binary_search(callback, lo, hi):
  mid = math.ceil((lo + hi) / 2)
  comparison = callback(mid)
  if comparison.find('<') != -1:
    binary_search(callback, mid, hi)
  elif comparison.find('>') != -1:
    binary_search(callback, lo, mid)
  else:
    # Even though I say it's y, you play again is you say something that contains y or Y
    if input("Yay! I win! Play again? (y/N): ").lower().find("y") != -1:
      print("")
      start_game(100)

print("Think of a number 1-100.\nI'll try to guess it within 7 takes!")
start_game(100)