Sfoglia il codice sorgente

Switched to closed list agent model.

Stocarson 9 anni fa
parent
commit
a390202fbd
2 ha cambiato i file con 49 aggiunte e 12 eliminazioni
  1. 25 7
      agent.py
  2. 24 5
      environment.py

+ 25 - 7
agent.py

@@ -1,14 +1,32 @@
 #!/usr/bin/env python3
 
-from environment import State, goalTest, actions, result
+from environment import State, goalTest, actions, result, equals
 from collections import deque
 
-# Example of goal-oriented agent.
+class ClosedList:
+    """List with deep membership check"""
+
+    def __init__(self):
+        self.list = []
+
+    def append(self, state):
+        self.list.append(state)
 
+    def contains(self, state):
+        for elem in self.list:
+            if equals(elem, state):
+                return True
+        return False
+
+# Example of goal-oriented agent.
 frontier = deque() # Initialize the frontier as a queue
-state = State() # Generate the initial state
-while not goalTest(state): # Apply the global test
-    for action in actions(state): # Expand the node
-        frontier.append(result(state, action))
-    state = frontier.popleft()
+closedList = ClosedList() # Initialize the closed list as a list
+node = State() # Generate the initial state
+while not goalTest(node): # Apply the goal test
+    for action in actions(node): # Expand the node
+        frontier.append(result(node, action))
+    node = frontier.popleft()
+    while closedList.contains(node):
+        node = frontier.popleft()
+    closedList.append(node)
 state.printState()

+ 24 - 5
environment.py

@@ -15,6 +15,22 @@ class State:
         elements = [x for x in range(MAX_SIZE**2)]
         shuffle(elements)
         self.matrix = [[elements[x+(y*MAX_SIZE)] for x in range(MAX_SIZE)] for y in range(MAX_SIZE)]
+
+    def __iter__(self):
+        self.row = 0
+        self.col = 0
+        return self
+
+    def __next__(self):
+        if self.row == MAX_SIZE:
+            self.row = 0
+            self.col = self.col+1
+        if self.col == MAX_SIZE:
+            raise StopIteration
+        elem = self.matrix[self.col][self.row]
+        self.row = self.row + 1
+        return elem
+
     def printState(self):
         for i in range(MAX_SIZE):
             print(self.matrix[i])
@@ -66,11 +82,14 @@ def result(state, action):
 
 def goalTest(state):
     el = []
-    for row in state.matrix:
-        el.extend(row)
+    for cell in state:
+        el.append(cell)
     return all(el[i] < el[i+1] for i in range(len(el)-1))
 
+def equals(firstState, secondState):
+    if firstState == secondState:
+        return True
+    return all(x[0]==x[1] for x in zip(firstState, secondState))
+
 if __name__ == "__main__":
-    s0 = State()
-    for action in actions(s0):
-        result(s0, action).printState()
+    pass