proffreda

Application of Recursive Data: Decision Trees

Apr 6th, 2016
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. class Tree:
  2. def __init__(self, cargo, left=None, right=None):
  3. self.cargo = cargo
  4. self.left = left
  5. self.right = right
  6.  
  7. def yes(ques):
  8. ans = str(input(ques)).lower()
  9. return ans[0] == "y"
  10.  
  11. def walkDecisionTree(root):
  12. while root.left is not None:
  13. prompt = root.cargo + "? "
  14. if yes(prompt):
  15. root = root.right
  16. else:
  17. root = root.left
  18. answernode = root
  19. return answernode
  20.  
  21. def addNewQ(leaf):
  22. oldguess= leaf.cargo
  23. prompt = "What is the animal's name?"
  24. newanimal = input(prompt)
  25. prompt = "What question would distinguish a {0} from a {1}? "
  26. question = input(prompt.format(newanimal, oldguess))
  27. leaf.cargo = question
  28. prompt = "If the animal were {0} the answer would be? "
  29. if yes(prompt.format(newanimal)):
  30. leaf.left = Tree(oldguess)
  31. leaf.right = Tree(newanimal)
  32. else:
  33. leaf.left = Tree(newanimal)
  34. leaf.right = Tree(oldguess)
  35.  
  36.  
  37. def animalQnA(root):
  38. # Loop until the user quits
  39. while True:
  40. print()
  41. if not yes("Are you thinking of an animal? "): break
  42. answernode = walkDecisionTree(root)
  43. prompt = "Is it a " + answernode.cargo + "? "
  44. if yes(prompt):
  45. print("I rule!")
  46. else:
  47. addNewQ(answernode)
  48.  
  49.  
  50. def printAllAnimals(t):
  51. global animalCounter
  52. if t.left == None:
  53. print(animalCounter, t.cargo)
  54. animalCounter += 1
  55. else:
  56. printAllAnimals(t.left)
  57. printAllAnimals(t.right)
  58.  
  59. root = Tree("Have fur",Tree("bird"),Tree("cat"))
  60. animalQnA(root)
  61. print("Q&A is over: Here are animals")
  62. animalCounter = 0
  63. printAllAnimals(root)
Advertisement
Add Comment
Please, Sign In to add comment