My solutions to Harvard's online course CS50AI, An Introduction to Machine Learning
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.1 KiB

4 years ago
  1. class Node():
  2. def __init__(self, state, parent, action):
  3. self.state = state
  4. self.parent = parent
  5. self.action = action
  6. def draw_path(self):
  7. path = []
  8. node = self
  9. while node.parent:
  10. path.append((node.action, node.state))
  11. node = node.parent
  12. path.reverse()
  13. return path
  14. class StackFrontier():
  15. def __init__(self):
  16. self.frontier = []
  17. def add(self, node):
  18. self.frontier.append(node)
  19. def contains_state(self, state):
  20. return any(node.state == state for node in self.frontier)
  21. def empty(self):
  22. return len(self.frontier) == 0
  23. def remove(self):
  24. if self.empty():
  25. raise Exception("empty frontier")
  26. else:
  27. node = self.frontier[-1]
  28. self.frontier = self.frontier[:-1]
  29. return node
  30. class QueueFrontier(StackFrontier):
  31. def remove(self):
  32. if self.empty():
  33. raise Exception("empty frontier")
  34. else:
  35. node = self.frontier[0]
  36. self.frontier = self.frontier[1:]
  37. return node