Advertisement
evitanasevska

Explorer Easy

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