Created
March 7, 2016 14:32
-
-
Save JeffCohen/483dc161784c82d00113 to your computer and use it in GitHub Desktop.
Exercise #23, using a binary tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TreeNode: | |
def __init__(self, content): | |
self.content = content | |
self.yes = None | |
self.no = None | |
def is_question(self): | |
return (self.yes != None or self.no != None) | |
# Prepare the decision tree | |
root = TreeNode('Is the car silent when you turn the key?') | |
root.yes = TreeNode('Are the battery terminals corroded?') | |
root.no = TreeNode('Does the car make a clicking noise?') | |
root.yes.yes = TreeNode('Clean terminals and try starting again.') | |
root.yes.no = TreeNode('Replace cables and try again.') | |
root.no.yes = TreeNode('Replace the battery.') | |
root.no.no = TreeNode('Does the car crank up but fail to start?') | |
root.no.no.yes = TreeNode('Check spark plug connections.') | |
root.no.no.no = TreeNode('Does the engine start and then die?') | |
root.no.no.no.yes = TreeNode('Does your car have fuel injection?') | |
root.no.no.no.yes.yes = TreeNode('Get it in for service.') | |
root.no.no.no.yes.no = TreeNode('Check to ensure the choke is opening and closing.') | |
# Now we can start asking questions | |
current_node = root | |
while current_node: | |
if current_node.is_question(): | |
answer = input(current_node.content + ' ') | |
if answer.lower()[0] == 'y': | |
current_node = current_node.yes | |
else: | |
current_node = current_node.no | |
if current_node is None: | |
print("I don't know what's wrong. Good luck!") | |
else: | |
print(current_node.content) | |
current_node = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment