Advertisement
cimona

Explorer (Neinformirano)

Jan 28th, 2019
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.18 KB | None | 0 0
  1. # Python modul vo koj se implementirani algoritmite za neinformirano i informirano prebaruvanje
  2.  
  3. # ______________________________________________________________________________________________
  4. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  5.  
  6. import sys
  7. import bisect
  8.  
  9. infinity = float('inf')  # sistemski definirana vrednost za beskonecnost
  10.  
  11.  
  12. # ______________________________________________________________________________________________
  13. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  14.  
  15. class Queue:
  16.     """Queue is an abstract class/interface. There are three types:
  17.        Stack(): A Last In First Out Queue.
  18.        FIFOQueue(): A First In First Out Queue.
  19.        PriorityQueue(order, f): Queue in sorted order (default min-first).
  20.    Each type supports the following methods and functions:
  21.        q.append(item)  -- add an item to the queue
  22.        q.extend(items) -- equivalent to: for item in items: q.append(item)
  23.        q.pop()         -- return the top item from the queue
  24.        len(q)          -- number of items in q (also q.__len())
  25.        item in q       -- does q contain item?
  26.    Note that isinstance(Stack(), Queue) is false, because we implement stacks
  27.    as lists.  If Python ever gets interfaces, Queue will be an interface."""
  28.  
  29.     def __init__(self):
  30.         raise NotImplementedError
  31.  
  32.     def extend(self, items):
  33.         for item in items:
  34.             self.append(item)
  35.  
  36.  
  37. def Stack():
  38.     """A Last-In-First-Out Queue."""
  39.     return []
  40.  
  41.  
  42. class FIFOQueue(Queue):
  43.     """A First-In-First-Out Queue."""
  44.  
  45.     def __init__(self):
  46.         self.A = []
  47.         self.start = 0
  48.  
  49.     def append(self, item):
  50.         self.A.append(item)
  51.  
  52.     def __len__(self):
  53.         return len(self.A) - self.start
  54.  
  55.     def extend(self, items):
  56.         self.A.extend(items)
  57.  
  58.     def pop(self):
  59.         e = self.A[self.start]
  60.         self.start += 1
  61.         if self.start > 5 and self.start > len(self.A) / 2:
  62.             self.A = self.A[self.start:]
  63.             self.start = 0
  64.         return e
  65.  
  66.     def __contains__(self, item):
  67.         return item in self.A[self.start:]
  68.  
  69.  
  70. class PriorityQueue(Queue):
  71.     """A queue in which the minimum (or maximum) element (as determined by f and
  72.    order) is returned first. If order is min, the item with minimum f(x) is
  73.    returned first; if order is max, then it is the item with maximum f(x).
  74.    Also supports dict-like lookup. This structure will be most useful in informed searches"""
  75.  
  76.     def __init__(self, order=min, f=lambda x: x):
  77.         self.A = []
  78.         self.order = order
  79.         self.f = f
  80.  
  81.     def append(self, item):
  82.         bisect.insort(self.A, (self.f(item), item))
  83.  
  84.     def __len__(self):
  85.         return len(self.A)
  86.  
  87.     def pop(self):
  88.         if self.order == min:
  89.             return self.A.pop(0)[1]
  90.         else:
  91.             return self.A.pop()[1]
  92.  
  93.     def __contains__(self, item):
  94.         return any(item == pair[1] for pair in self.A)
  95.  
  96.     def __getitem__(self, key):
  97.         for _, item in self.A:
  98.             if item == key:
  99.                 return item
  100.  
  101.     def __delitem__(self, key):
  102.         for i, (value, item) in enumerate(self.A):
  103.             if item == key:
  104.                 self.A.pop(i)
  105.  
  106.  
  107. # ______________________________________________________________________________________________
  108. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  109. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  110. # na sekoj eden problem sto sakame da go resime
  111.  
  112.  
  113. class Problem:
  114.     """The abstract class for a formal problem.  You should subclass this and
  115.    implement the method successor, and possibly __init__, goal_test, and
  116.    path_cost. Then you will create instances of your subclass and solve them
  117.    with the various search functions."""
  118.  
  119.     def __init__(self, initial, goal=None):
  120.         """The constructor specifies the initial state, and possibly a goal
  121.        state, if there is a unique goal.  Your subclass's constructor can add
  122.        other arguments."""
  123.         self.initial = initial
  124.         self.goal = goal
  125.  
  126.     def successor(self, state):
  127.         """Given a state, return a dictionary of {action : state} pairs reachable
  128.        from this state. If there are many successors, consider an iterator
  129.        that yields the successors one at a time, rather than building them
  130.        all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  131.         raise NotImplementedError
  132.  
  133.     def actions(self, state):
  134.         """Given a state, return a list of all actions possible from that state"""
  135.         raise NotImplementedError
  136.  
  137.     def result(self, state, action):
  138.         """Given a state and action, return the resulting state"""
  139.         raise NotImplementedError
  140.  
  141.     def goal_test(self, state):
  142.         """Return True if the state is a goal. The default method compares the
  143.        state to self.goal, as specified in the constructor. Implement this
  144.        method if checking against a single self.goal is not enough."""
  145.         return state == self.goal
  146.  
  147.     def path_cost(self, c, state1, action, state2):
  148.         """Return the cost of a solution path that arrives at state2 from
  149.        state1 via action, assuming cost c to get up to state1. If the problem
  150.        is such that the path doesn't matter, this function will only look at
  151.        state2.  If the path does matter, it will consider c and maybe state1
  152.        and action. The default method costs 1 for every step in the path."""
  153.         return c + 1
  154.  
  155.     def value(self):
  156.         """For optimization problems, each state has a value.  Hill-climbing
  157.        and related algorithms try to maximize this value."""
  158.         raise NotImplementedError
  159.  
  160.  
  161. # ______________________________________________________________________________
  162. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  163. # Klasata Node ne se nasleduva
  164.  
  165. class Node:
  166.     """A node in a search tree. Contains a pointer to the parent (the node
  167.    that this is a successor of) and to the actual state for this node. Note
  168.    that if a state is arrived at by two paths, then there are two nodes with
  169.    the same state.  Also includes the action that got us to this state, and
  170.    the total path_cost (also known as g) to reach the node.  Other functions
  171.    may add an f and h value; see best_first_graph_search and astar_search for
  172.    an explanation of how the f and h values are handled. You will not need to
  173.    subclass this class."""
  174.  
  175.     def __init__(self, state, parent=None, action=None, path_cost=0):
  176.         "Create a search tree Node, derived from a parent by an action."
  177.         self.state = state
  178.         self.parent = parent
  179.         self.action = action
  180.         self.path_cost = path_cost
  181.         self.depth = 0
  182.         if parent:
  183.             self.depth = parent.depth + 1
  184.  
  185.     def __repr__(self):
  186.         return "<Node %s>" % (self.state,)
  187.  
  188.     def __lt__(self, node):
  189.         return self.state < node.state
  190.  
  191.     def expand(self, problem):
  192.         "List the nodes reachable in one step from this node."
  193.         return [self.child_node(problem, action)
  194.                 for action in problem.actions(self.state)]
  195.  
  196.     def child_node(self, problem, action):
  197.         "Return a child node from this node"
  198.         next = problem.result(self.state, action)
  199.         return Node(next, self, action,
  200.                     problem.path_cost(self.path_cost, self.state,
  201.                                       action, next))
  202.  
  203.     def solution(self):
  204.         "Return the sequence of actions to go from the root to this node."
  205.         return [node.action for node in self.path()[1:]]
  206.  
  207.     def solve(self):
  208.         "Return the sequence of states to go from the root to this node."
  209.         return [node.state for node in self.path()[0:]]
  210.  
  211.     def path(self):
  212.         "Return a list of nodes forming the path from the root to this node."
  213.         x, result = self, []
  214.         while x:
  215.             result.append(x)
  216.             x = x.parent
  217.         return list(reversed(result))
  218.  
  219.     # We want for a queue of nodes in breadth_first_search or
  220.     # astar_search to have no duplicated states, so we treat nodes
  221.     # with the same state as equal. [Problem: this may not be what you
  222.     # want in other contexts.]
  223.  
  224.     def __eq__(self, other):
  225.         return isinstance(other, Node) and self.state == other.state
  226.  
  227.     def __hash__(self):
  228.         return hash(self.state)
  229.  
  230.  
  231. # ________________________________________________________________________________________________________
  232. #Neinformirano prebaruvanje vo ramki na drvo
  233. #Vo ramki na drvoto ne razresuvame jamki
  234.  
  235. def tree_search(problem, fringe):
  236.     """Search through the successors of a problem to find a goal.
  237.    The argument fringe should be an empty queue."""
  238.     fringe.append(Node(problem.initial))
  239.     while fringe:
  240.         node = fringe.pop()
  241.         print (node.state)
  242.         if problem.goal_test(node.state):
  243.             return node
  244.         fringe.extend(node.expand(problem))
  245.     return None
  246.  
  247.  
  248. def breadth_first_tree_search(problem):
  249.     "Search the shallowest nodes in the search tree first."
  250.     return tree_search(problem, FIFOQueue())
  251.  
  252.  
  253. def depth_first_tree_search(problem):
  254.     "Search the deepest nodes in the search tree first."
  255.     return tree_search(problem, Stack())
  256.  
  257.  
  258. # ________________________________________________________________________________________________________
  259. #Neinformirano prebaruvanje vo ramki na graf
  260. #Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  261.  
  262. def graph_search(problem, fringe):
  263.     """Search through the successors of a problem to find a goal.
  264.    The argument fringe should be an empty queue.
  265.    If two paths reach a state, only use the best one."""
  266.     closed = {}
  267.     fringe.append(Node(problem.initial))
  268.     while fringe:
  269.         node = fringe.pop()
  270.         if problem.goal_test(node.state):
  271.             return node
  272.         if node.state not in closed:
  273.             closed[node.state] = True
  274.             fringe.extend(node.expand(problem))
  275.     return None
  276.  
  277.  
  278. def breadth_first_graph_search(problem):
  279.     "Search the shallowest nodes in the search tree first."
  280.     return graph_search(problem, FIFOQueue())
  281.  
  282.  
  283. def depth_first_graph_search(problem):
  284.     "Search the deepest nodes in the search tree first."
  285.     return graph_search(problem, Stack())
  286.  
  287.  
  288. def uniform_cost_search(problem):
  289.     "Search the nodes in the search tree with lowest cost first."
  290.     return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  291.  
  292.  
  293. def depth_limited_search(problem, limit=50):
  294.     "depth first search with limited depth"
  295.  
  296.     def recursive_dls(node, problem, limit):
  297.         "helper function for depth limited"
  298.         cutoff_occurred = False
  299.         if problem.goal_test(node.state):
  300.             return node
  301.         elif node.depth == limit:
  302.             return 'cutoff'
  303.         else:
  304.             for successor in node.expand(problem):
  305.                 result = recursive_dls(successor, problem, limit)
  306.                 if result == 'cutoff':
  307.                     cutoff_occurred = True
  308.                 elif result != None:
  309.                     return result
  310.         if cutoff_occurred:
  311.             return 'cutoff'
  312.         else:
  313.             return None
  314.  
  315.     # Body of depth_limited_search:
  316.     return recursive_dls(Node(problem.initial), problem, limit)
  317.  
  318.  
  319. def iterative_deepening_search(problem):
  320.  
  321.     for depth in range(sys.maxsize):
  322.         result = depth_limited_search(problem, depth)
  323.         if result is not 'cutoff':
  324.             return result
  325.  
  326.  
  327.  
  328. # _________________________________________________________________________________________________________
  329.  
  330. paths = (
  331. ((1, 1), (1, 2)), ((1, 1), (2, 1)), ((1, 2), (2, 2)), ((2, 2), (2, 1)),
  332. ((3, 1), (3, 2)), ((3, 1), (4, 1)), ((3, 2), (4, 2)), ((4, 2), (4, 1)),
  333. ((1, 3), (1, 4)), ((1, 3), (2, 3)), ((1, 4), (2, 4)), ((2, 4), (2, 3)),
  334. ((3, 3), (3, 4)), ((3, 3), (4, 3)), ((3, 4), (4, 4)), ((4, 4), (4, 3)),
  335. ((2, 2), (2, 3)), ((2, 3), (3, 3)), ((3, 3), (3, 2)), ((3, 2), (2, 2)),
  336. ((2, 2), (3, 3))
  337. )
  338. circles = (
  339. (1, 1), (1, 2), (1, 3), (1, 4),
  340. (2, 1), (2, 2), (2, 3), (2, 4),
  341. (3, 1), (3, 2), (3, 3), (3, 4),
  342. (4, 1), (4, 2), (4, 3), (4, 4)
  343. )
  344. class Explorer(Problem):
  345.     def __init__(self, initial):
  346.         self.initial = initial
  347.  
  348.     def goal_test(self, state):
  349.         return len(state[2]) == 0
  350.  
  351.     def successor(self, state):
  352.  
  353.         successors = dict()
  354.         x, y = state[0], state[1]
  355.         stars = state[2]
  356.         allowed_circles = state[3]
  357.  
  358.         # Right
  359.         if y < 4:
  360.             x_new = x
  361.             y_new = y + 1
  362.             j = -1
  363.  
  364.             for i in range(len(circles)):
  365.                 if (x_new, y_new) == circles[i]:
  366.                     j = i
  367.  
  368.             if j != -1 and allowed_circles[j] != '0':
  369.                 for i in range(len(paths)):
  370.                     if ((x_new, y_new), (x, y)) == paths[i] or ((x, y), (x_new, y_new)) == paths[i]:
  371.                         stars_new = tuple(star for star in stars if star != (x_new, y_new))
  372.                         allowed_circles_new = allowed_circles[:j] + \
  373.                                               chr(int(allowed_circles[j]) - 1 + 48) + allowed_circles[j + 1:]
  374.                         state_new = (x_new, y_new, stars_new, allowed_circles_new)
  375.                         successors['Right'] = state_new
  376.  
  377.         # Left
  378.         if y > 1:
  379.             x_new = x
  380.             y_new = y - 1
  381.             j = -1
  382.  
  383.             for i in range(len(circles)):
  384.                 if (x_new, y_new) == circles[i]:
  385.                     j = i
  386.  
  387.             if j != -1 and allowed_circles[j] != '0':
  388.                 for i in range(len(paths)):
  389.                     if ((x_new, y_new), (x, y)) == paths[i] or ((x, y), (x_new, y_new)) == paths[i]:
  390.                         stars_new = tuple(star for star in stars if star != (x_new, y_new))
  391.                         allowed_circles_new = allowed_circles[:j] + \
  392.                                               chr(int(allowed_circles[j]) - 1 + 48) + allowed_circles[j + 1:]
  393.                         state_new = (x_new, y_new, stars_new, allowed_circles_new)
  394.                         successors['Left'] = state_new
  395.  
  396.         # Up
  397.         if x > 1:
  398.             x_new = x - 1
  399.             y_new = y
  400.             j = -1
  401.  
  402.             for i in range(len(circles)):
  403.                 if (x_new, y_new) == circles[i]:
  404.                     j = i
  405.  
  406.             if j != -1 and allowed_circles[j] != '0':
  407.                 for i in range(len(paths)):
  408.                     if ((x_new, y_new), (x, y)) == paths[i] or ((x, y), (x_new, y_new)) == paths[i]:
  409.                         stars_new = tuple(star for star in stars if star != (x_new, y_new))
  410.                         allowed_circles_new = allowed_circles[:j] + \
  411.                                               chr(int(allowed_circles[j]) - 1 + 48) + allowed_circles[j + 1:]
  412.                         state_new = (x_new, y_new, stars_new, allowed_circles_new)
  413.                         successors['Up'] = state_new
  414.  
  415.         # Down
  416.         if x < 4:
  417.             x_new = x + 1
  418.             y_new = y
  419.             j = -1
  420.  
  421.             for i in range(len(circles)):
  422.                 if (x_new, y_new) == circles[i]:
  423.                     j = i
  424.  
  425.             if j != -1 and allowed_circles[j] != '0':
  426.                 for i in range(len(paths)):
  427.                     if ((x_new, y_new), (x, y)) == paths[i] or ((x, y), (x_new, y_new)) == paths[i]:
  428.                         stars_new = tuple(star for star in stars if star != (x_new, y_new))
  429.                         allowed_circles_new = allowed_circles[:j] + chr(
  430.                         int(allowed_circles[j]) - 1 + 48) + allowed_circles[j + 1:]
  431.                         state_new = (x_new, y_new, stars_new, allowed_circles_new)
  432.                         successors['Down'] = state_new
  433.  
  434.         # Diagonal Down
  435.         if x == 2 and y == 2:
  436.             x_new = x + 1
  437.             y_new = y + 1
  438.             j = -1
  439.             for i in range(len(circles)):
  440.                 if (x_new, y_new) == circles[i]:
  441.                     j = i
  442.  
  443.             if j != -1 and allowed_circles[j] != '0':
  444.                 for i in range(len(paths)):
  445.                     if ((x_new, y_new), (x, y)) == paths[i] or ((x, y), (x_new, y_new)) == paths[i]:
  446.                         stars_new = tuple(star for star in stars if star != (x_new, y_new))
  447.                         allowed_circles_new = allowed_circles[:j] + \
  448.                                               chr(int(allowed_circles[j]) - 1 + 48) + allowed_circles[j + 1:]
  449.                         state_new = (x_new, y_new, stars_new, allowed_circles_new)
  450.                         successors['Diagonal down'] = state_new
  451.  
  452.         # Diagonal Up
  453.         if x == 3 and y == 3:
  454.             x_new = x - 1
  455.             y_new = y - 1
  456.             j = -1
  457.  
  458.             for i in range(len(circles)):
  459.                 if (x_new, y_new) == circles[i]:
  460.                     j = i
  461.  
  462.             if j != -1 and allowed_circles[j] != '0':
  463.                 for i in range(len(paths)):
  464.                     if ((x_new, y_new), (x, y)) == paths[i] or ((x, y), (x_new, y_new)) == paths[i]:
  465.                         stars_new = tuple(star for star in stars if star != (x_new, y_new))
  466.                         allowed_circles_new = allowed_circles[:j] + \
  467.                                               chr(int(allowed_circles[j]) - 1 + 48) + allowed_circles[j + 1:]
  468.                         state_new = (x_new, y_new, stars_new, allowed_circles_new)
  469.                         successors['Diagonal up'] = state_new
  470.  
  471.         return successors
  472.  
  473.     def actions(self, state):
  474.         return self.successor(state).keys()
  475.  
  476.     def result(self, state, action):
  477.         return self.successor(state)[action]
  478.  
  479. human_row = int(input())
  480. human_column = int(input())
  481. star1_row = int(input())
  482. star1_column = int(input())
  483. star2_row = int(input())
  484. star2_column = int(input())
  485. explorer_instance = Explorer((human_row, human_column, ((star1_row, star1_column), (star2_row, star2_column)),
  486. '1111122112211111'))
  487. print(breadth_first_graph_search(explorer_instance).solution())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement