import pickle
import os
class Node:
def __init__(self, question=None, animal=None):
self.question = question
self.animal = animal
self.yes = None
self.no = None
def is_leaf(self):
return self.animal is not None
def ask_yes_no(prompt):
while True:
ans = input(prompt + ” (y/n): “).strip().lower()
if ans in [‘y’, ‘yes’]:
return True
elif ans in [‘n’, ‘no’]:
return False
print(“Please enter y or n.”)
def play(node):
if node.is_leaf():
if ask_yes_no(f”Is it a {node.animal}?”):
print(“Yay! I guessed it!”)
return node
else:
return learn(node)
else:
if ask_yes_no(node.question):
node.yes = play(node.yes)
else:
node.no = play(node.no)
return node
def learn(old_node):
new_animal = input(“I give up! What animal were you thinking of? “).strip()
question = input(f”Give me a yes/no question to tell a {new_animal} from a {old_node.animal}: “).strip()
if ask_yes_no(f”For a {new_animal}, what is the answer to your question?”):
new_node = Node(question=question)
new_node.yes = Node(animal=new_animal)
new_node.no = old_node
else:
new_node = Node(question=question)
new_node.no = Node(animal=new_animal)
new_node.yes = old_node
print(“Thanks! I’ll remember that.”)
return new_node
def save_tree(tree, filename=”animal_tree.pkl”):
with open(filename, “wb”) as f:
pickle.dump(tree, f)
def load_tree(filename=”animal_tree.pkl”):
if os.path.exists(filename):
with open(filename, “rb”) as f:
return pickle.load(f)
else:
# Start with a default animal
return Node(animal=”cat”)
def main():
print(“Think of an animal, and I’ll try to guess it!”)
tree = load_tree()
tree = play(tree)
save_tree(tree)
if __name__ == “__main__”:
while True:
main()
if not ask_yes_no(“Play again?”):
break