Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Tree:
- def __init__(self, cargo, left=None, right=None):
- self.cargo = cargo
- self.left = left
- self.right = right
- def yes(ques):
- ans = str(input(ques)).lower()
- return ans[0] == "y"
- def walkDecisionTree(root):
- while root.left is not None:
- prompt = root.cargo + "? "
- if yes(prompt):
- root = root.right
- else:
- root = root.left
- answernode = root
- return answernode
- def addNewQ(leaf):
- oldguess= leaf.cargo
- prompt = "What is the animal's name?"
- newanimal = input(prompt)
- prompt = "What question would distinguish a {0} from a {1}? "
- question = input(prompt.format(newanimal, oldguess))
- leaf.cargo = question
- prompt = "If the animal were {0} the answer would be? "
- if yes(prompt.format(newanimal)):
- leaf.left = Tree(oldguess)
- leaf.right = Tree(newanimal)
- else:
- leaf.left = Tree(newanimal)
- leaf.right = Tree(oldguess)
- def animalQnA(root):
- # Loop until the user quits
- while True:
- print()
- if not yes("Are you thinking of an animal? "): break
- answernode = walkDecisionTree(root)
- prompt = "Is it a " + answernode.cargo + "? "
- if yes(prompt):
- print("I rule!")
- else:
- addNewQ(answernode)
- def printAllAnimals(t):
- global animalCounter
- if t.left == None:
- print(animalCounter, t.cargo)
- animalCounter += 1
- else:
- printAllAnimals(t.left)
- printAllAnimals(t.right)
- root = Tree("Have fur",Tree("bird"),Tree("cat"))
- animalQnA(root)
- print("Q&A is over: Here are animals")
- animalCounter = 0
- printAllAnimals(root)
Advertisement
Add Comment
Please, Sign In to add comment