Advertisement
Guest User

Untitled

a guest
Apr 19th, 2018
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 48.04 KB | None | 0 0
  1. #Prva
  2. Pocetok = input()
  3. Stanica1 = input()
  4. Stanica2 = input()
  5. Kraj = input()
  6. # Python modul vo koj se implementirani algoritmite za neinformirano i informirano prebaruvanje
  7.  
  8. # ______________________________________________________________________________________________
  9. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  10.  
  11. import sys
  12. import bisect
  13.  
  14. infinity = float('inf')  # sistemski definirana vrednost za beskonecnost
  15.  
  16.  
  17. # ______________________________________________________________________________________________
  18. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  19.  
  20. class Queue:
  21.     """Queue is an abstract class/interface. There are three types:
  22.        Stack(): A Last In First Out Queue.
  23.        FIFOQueue(): A First In First Out Queue.
  24.        PriorityQueue(order, f): Queue in sorted order (default min-first).
  25.    Each type supports the following methods and functions:
  26.        q.append(item)  -- add an item to the queue
  27.        q.extend(items) -- equivalent to: for item in items: q.append(item)
  28.        q.pop()         -- return the top item from the queue
  29.        len(q)          -- number of items in q (also q.__len())
  30.        item in q       -- does q contain item?
  31.    Note that isinstance(Stack(), Queue) is false, because we implement stacks
  32.    as lists.  If Python ever gets interfaces, Queue will be an interface."""
  33.  
  34.     def __init__(self):
  35.         raise NotImplementedError
  36.  
  37.     def extend(self, items):
  38.         for item in items:
  39.             self.append(item)
  40.  
  41.  
  42. def Stack():
  43.     """A Last-In-First-Out Queue."""
  44.     return []
  45.  
  46.  
  47. class FIFOQueue(Queue):
  48.     """A First-In-First-Out Queue."""
  49.  
  50.     def __init__(self):
  51.         self.A = []
  52.         self.start = 0
  53.  
  54.     def append(self, item):
  55.         self.A.append(item)
  56.  
  57.     def __len__(self):
  58.         return len(self.A) - self.start
  59.  
  60.     def extend(self, items):
  61.         self.A.extend(items)
  62.  
  63.     def pop(self):
  64.         e = self.A[self.start]
  65.         self.start += 1
  66.         if self.start > 5 and self.start > len(self.A) / 2:
  67.             self.A = self.A[self.start:]
  68.             self.start = 0
  69.         return e
  70.  
  71.     def __contains__(self, item):
  72.         return item in self.A[self.start:]
  73.  
  74.  
  75. class PriorityQueue(Queue):
  76.     """A queue in which the minimum (or maximum) element (as determined by f and
  77.    order) is returned first. If order is min, the item with minimum f(x) is
  78.    returned first; if order is max, then it is the item with maximum f(x).
  79.    Also supports dict-like lookup. This structure will be most useful in informed searches"""
  80.  
  81.     def __init__(self, order=min, f=lambda x: x):
  82.         self.A = []
  83.         self.order = order
  84.         self.f = f
  85.  
  86.     def append(self, item):
  87.         bisect.insort(self.A, (self.f(item), item))
  88.  
  89.     def __len__(self):
  90.         return len(self.A)
  91.  
  92.     def pop(self):
  93.         if self.order == min:
  94.             return self.A.pop(0)[1]
  95.         else:
  96.             return self.A.pop()[1]
  97.  
  98.     def __contains__(self, item):
  99.         return any(item == pair[1] for pair in self.A)
  100.  
  101.     def __getitem__(self, key):
  102.         for _, item in self.A:
  103.             if item == key:
  104.                 return item
  105.  
  106.     def __delitem__(self, key):
  107.         for i, (value, item) in enumerate(self.A):
  108.             if item == key:
  109.                 self.A.pop(i)
  110.  
  111.  
  112. # ______________________________________________________________________________________________
  113. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  114. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  115. # na sekoj eden problem sto sakame da go resime
  116.  
  117.  
  118. class Problem:
  119.     """The abstract class for a formal problem.  You should subclass this and
  120.    implement the method successor, and possibly __init__, goal_test, and
  121.    path_cost. Then you will create instances of your subclass and solve them
  122.    with the various search functions."""
  123.  
  124.     def __init__(self, initial, goal=None):
  125.         """The constructor specifies the initial state, and possibly a goal
  126.        state, if there is a unique goal.  Your subclass's constructor can add
  127.        other arguments."""
  128.         self.initial = initial
  129.         self.goal = goal
  130.  
  131.     def successor(self, state):
  132.         """Given a state, return a dictionary of {action : state} pairs reachable
  133.        from this state. If there are many successors, consider an iterator
  134.        that yields the successors one at a time, rather than building them
  135.        all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  136.         raise NotImplementedError
  137.  
  138.     def actions(self, state):
  139.         """Given a state, return a list of all actions possible from that state"""
  140.         raise NotImplementedError
  141.  
  142.     def result(self, state, action):
  143.         """Given a state and action, return the resulting state"""
  144.         raise NotImplementedError
  145.  
  146.     def goal_test(self, state):
  147.         """Return True if the state is a goal. The default method compares the
  148.        state to self.goal, as specified in the constructor. Implement this
  149.        method if checking against a single self.goal is not enough."""
  150.         return state == self.goal
  151.  
  152.     def path_cost(self, c, state1, action, state2):
  153.         """Return the cost of a solution path that arrives at state2 from
  154.        state1 via action, assuming cost c to get up to state1. If the problem
  155.        is such that the path doesn't matter, this function will only look at
  156.        state2.  If the path does matter, it will consider c and maybe state1
  157.        and action. The default method costs 1 for every step in the path."""
  158.         return c + 1
  159.  
  160.     def value(self):
  161.         """For optimization problems, each state has a value.  Hill-climbing
  162.        and related algorithms try to maximize this value."""
  163.         raise NotImplementedError
  164.  
  165.  
  166. # ______________________________________________________________________________
  167. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  168. # Klasata Node ne se nasleduva
  169.  
  170. class Node:
  171.     """A node in a search tree. Contains a pointer to the parent (the node
  172.    that this is a successor of) and to the actual state for this node. Note
  173.    that if a state is arrived at by two paths, then there are two nodes with
  174.    the same state.  Also includes the action that got us to this state, and
  175.    the total path_cost (also known as g) to reach the node.  Other functions
  176.    may add an f and h value; see best_first_graph_search and astar_search for
  177.    an explanation of how the f and h values are handled. You will not need to
  178.    subclass this class."""
  179.  
  180.     def __init__(self, state, parent=None, action=None, path_cost=0):
  181.         "Create a search tree Node, derived from a parent by an action."
  182.         self.state = state
  183.         self.parent = parent
  184.         self.action = action
  185.         self.path_cost = path_cost
  186.         self.depth = 0
  187.         if parent:
  188.             self.depth = parent.depth + 1
  189.  
  190.     def __repr__(self):
  191.         return "<Node %s>" % (self.state,)
  192.  
  193.     def __lt__(self, node):
  194.         return self.state < node.state
  195.  
  196.     def expand(self, problem):
  197.         "List the nodes reachable in one step from this node."
  198.         return [self.child_node(problem, action)
  199.                 for action in problem.actions(self.state)]
  200.  
  201.     def child_node(self, problem, action):
  202.         "Return a child node from this node"
  203.         next = problem.result(self.state, action)
  204.         return Node(next, self, action,
  205.                     problem.path_cost(self.path_cost, self.state,
  206.                                       action, next))
  207.  
  208.     def solution(self):
  209.         "Return the sequence of actions to go from the root to this node."
  210.         return [node.action for node in self.path()[1:]]
  211.  
  212.     def solve(self):
  213.         "Return the sequence of states to go from the root to this node."
  214.         return [node.state for node in self.path()[0:]]
  215.  
  216.     def path(self):
  217.         "Return a list of nodes forming the path from the root to this node."
  218.         x, result = self, []
  219.         while x:
  220.             result.append(x)
  221.             x = x.parent
  222.         return list(reversed(result))
  223.  
  224.     # We want for a queue of nodes in breadth_first_search or
  225.     # astar_search to have no duplicated states, so we treat nodes
  226.     # with the same state as equal. [Problem: this may not be what you
  227.     # want in other contexts.]
  228.  
  229.     def __eq__(self, other):
  230.         return isinstance(other, Node) and self.state == other.state
  231.  
  232.     def __hash__(self):
  233.         return hash(self.state)
  234.  
  235.  
  236. # ________________________________________________________________________________________________________
  237. #Neinformirano prebaruvanje vo ramki na drvo
  238. #Vo ramki na drvoto ne razresuvame jamki
  239.  
  240. def tree_search(problem, fringe):
  241.     """Search through the successors of a problem to find a goal.
  242.    The argument fringe should be an empty queue."""
  243.     fringe.append(Node(problem.initial))
  244.     while fringe:
  245.         node = fringe.pop()
  246.        
  247.         if problem.goal_test(node.state):
  248.             return node
  249.         fringe.extend(node.expand(problem))
  250.     return None
  251.  
  252.  
  253. def breadth_first_tree_search(problem):
  254.     "Search the shallowest nodes in the search tree first."
  255.     return tree_search(problem, FIFOQueue())
  256.  
  257.  
  258. def depth_first_tree_search(problem):
  259.     "Search the deepest nodes in the search tree first."
  260.     return tree_search(problem, Stack())
  261.  
  262.  
  263. # ________________________________________________________________________________________________________
  264. #Neinformirano prebaruvanje vo ramki na graf
  265. #Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  266.  
  267. def graph_search(problem, fringe):
  268.     """Search through the successors of a problem to find a goal.
  269.    The argument fringe should be an empty queue.
  270.    If two paths reach a state, only use the best one."""
  271.     closed = {}
  272.     fringe.append(Node(problem.initial))
  273.     while fringe:
  274.         node = fringe.pop()
  275.         if problem.goal_test(node.state):
  276.             return node
  277.         if node.state not in closed:
  278.             closed[node.state] = True
  279.             fringe.extend(node.expand(problem))
  280.     return None
  281.  
  282.  
  283. def breadth_first_graph_search(problem):
  284.     "Search the shallowest nodes in the search tree first."
  285.     return graph_search(problem, FIFOQueue())
  286.  
  287.  
  288. def depth_first_graph_search(problem):
  289.     "Search the deepest nodes in the search tree first."
  290.     return graph_search(problem, Stack())
  291.  
  292.  
  293. def uniform_cost_search(problem):
  294.     "Search the nodes in the search tree with lowest cost first."
  295.     return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  296.  
  297.  
  298. def depth_limited_search(problem, limit=50):
  299.     "depth first search with limited depth"
  300.  
  301.     def recursive_dls(node, problem, limit):
  302.         "helper function for depth limited"
  303.         cutoff_occurred = False
  304.         if problem.goal_test(node.state):
  305.             return node
  306.         elif node.depth == limit:
  307.             return 'cutoff'
  308.         else:
  309.             for successor in node.expand(problem):
  310.                 result = recursive_dls(successor, problem, limit)
  311.                 if result == 'cutoff':
  312.                     cutoff_occurred = True
  313.                 elif result != None:
  314.                     return result
  315.         if cutoff_occurred:
  316.             return 'cutoff'
  317.         else:
  318.             return None
  319.  
  320.     # Body of depth_limited_search:
  321.     return recursive_dls(Node(problem.initial), problem, limit)
  322.  
  323.  
  324. def iterative_deepening_search(problem):
  325.  
  326.     for depth in xrange(sys.maxint):
  327.         result = depth_limited_search(problem, depth)
  328.         if result is not 'cutoff':
  329.             return result
  330.  
  331.        
  332. # ________________________________________________________________________________________________________
  333. #Pomosna funkcija za informirani prebaruvanja
  334. #So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  335.  
  336. def memoize(fn, slot=None):
  337.     """Memoize fn: make it remember the computed value for any argument list.
  338.    If slot is specified, store result in that slot of first argument.
  339.    If slot is false, store results in a dictionary."""
  340.     if slot:
  341.         def memoized_fn(obj, *args):
  342.             if hasattr(obj, slot):
  343.                 return getattr(obj, slot)
  344.             else:
  345.                 val = fn(obj, *args)
  346.                 setattr(obj, slot, val)
  347.                 return val
  348.     else:
  349.         def memoized_fn(*args):
  350.             if not memoized_fn.cache.has_key(args):
  351.                 memoized_fn.cache[args] = fn(*args)
  352.             return memoized_fn.cache[args]
  353.  
  354.         memoized_fn.cache = {}
  355.     return memoized_fn
  356.  
  357.  
  358. # ________________________________________________________________________________________________________
  359. #Informirano prebaruvanje vo ramki na graf
  360.  
  361. def best_first_graph_search(problem, f):
  362.     """Search the nodes with the lowest f scores first.
  363.    You specify the function f(node) that you want to minimize; for example,
  364.    if f is a heuristic estimate to the goal, then we have greedy best
  365.    first search; if f is node.depth then we have breadth-first search.
  366.    There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  367.    values will be cached on the nodes as they are computed. So after doing
  368.    a best first search you can examine the f values of the path returned."""
  369.  
  370.     f = memoize(f, 'f')
  371.     node = Node(problem.initial)
  372.     if problem.goal_test(node.state):
  373.         return node
  374.     frontier = PriorityQueue(min, f)
  375.     frontier.append(node)
  376.     explored = set()
  377.     while frontier:
  378.         node = frontier.pop()
  379.         if problem.goal_test(node.state):
  380.             return node
  381.         explored.add(node.state)
  382.         for child in node.expand(problem):
  383.             if child.state not in explored and child not in frontier:
  384.                 frontier.append(child)
  385.             elif child in frontier:
  386.                 incumbent = frontier[child]
  387.                 if f(child) < f(incumbent):
  388.                     del frontier[incumbent]
  389.                     frontier.append(child)
  390.     return None
  391.  
  392.  
  393. def greedy_best_first_graph_search(problem, h=None):
  394.     "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  395.     h = memoize(h or problem.h, 'h')
  396.     return best_first_graph_search(problem, h)
  397.  
  398.  
  399. def astar_search(problem, h=None):
  400.     "A* search is best-first graph search with f(n) = g(n)+h(n)."
  401.     h = memoize(h or problem.h, 'h')
  402.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  403.  
  404.  
  405. # ________________________________________________________________________________________________________
  406. #Dopolnitelni prebaruvanja
  407. #Recursive_best_first_search e implementiran
  408. #Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  409.  
  410. def recursive_best_first_search(problem, h=None):
  411.     h = memoize(h or problem.h, 'h')
  412.  
  413.     def RBFS(problem, node, flimit):
  414.         if problem.goal_test(node.state):
  415.             return node, 0  # (The second value is immaterial)
  416.         successors = node.expand(problem)
  417.         if len(successors) == 0:
  418.             return None, infinity
  419.         for s in successors:
  420.             s.f = max(s.path_cost + h(s), node.f)
  421.         while True:
  422.             # Order by lowest f value
  423.             successors.sort(key=lambda x: x.f)
  424.             best = successors[0]
  425.             if best.f > flimit:
  426.                 return None, best.f
  427.             if len(successors) > 1:
  428.                 alternative = successors[1].f
  429.             else:
  430.                 alternative = infinity
  431.             result, best.f = RBFS(problem, best, min(flimit, alternative))
  432.             if result is not None:
  433.                 return result, best.f
  434.  
  435.     node = Node(problem.initial)
  436.     node.f = h(node)
  437.     result, bestf = RBFS(problem, node, infinity)
  438.     return result
  439.  
  440.  
  441. # Graphs and Graph Problems
  442. import math
  443.  
  444. def distance(a, b):
  445.     """The distance between two (x, y) points."""
  446.     return math.hypot((a[0] - b[0]), (a[1] - b[1]))
  447.    
  448.    
  449. class Graph:
  450.  
  451.     """A graph connects nodes (verticies) by edges (links).  Each edge can also
  452.    have a length associated with it.  The constructor call is something like:
  453.        g = Graph({'A': {'B': 1, 'C': 2})
  454.    this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from
  455.    A to B,  and an edge of length 2 from A to C.  You can also do:
  456.        g = Graph({'A': {'B': 1, 'C': 2}, directed=False)
  457.    This makes an undirected graph, so inverse links are also added. The graph
  458.    stays undirected; if you add more links with g.connect('B', 'C', 3), then
  459.    inverse link is also added.  You can use g.nodes() to get a list of nodes,
  460.    g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the
  461.    length of the link from A to B.  'Lengths' can actually be any object at
  462.    all, and nodes can be any hashable object."""
  463.  
  464.     def __init__(self, dict=None, directed=True):
  465.         self.dict = dict or {}
  466.         self.directed = directed
  467.         if not directed:
  468.             self.make_undirected()
  469.  
  470.     def make_undirected(self):
  471.         """Make a digraph into an undirected graph by adding symmetric edges."""
  472.         for a in list(self.dict.keys()):
  473.             for (b, dist) in self.dict[a].items():
  474.                 self.connect1(b, a, dist)
  475.  
  476.     def connect(self, A, B, distance=1):
  477.         """Add a link from A and B of given distance, and also add the inverse
  478.        link if the graph is undirected."""
  479.         self.connect1(A, B, distance)
  480.         if not self.directed:
  481.             self.connect1(B, A, distance)
  482.  
  483.     def connect1(self, A, B, distance):
  484.         """Add a link from A to B of given distance, in one direction only."""
  485.         self.dict.setdefault(A, {})[B] = distance
  486.  
  487.     def get(self, a, b=None):
  488.         """Return a link distance or a dict of {node: distance} entries.
  489.        .get(a,b) returns the distance or None;
  490.        .get(a) returns a dict of {node: distance} entries, possibly {}."""
  491.         links = self.dict.setdefault(a, {})
  492.         if b is None:
  493.             return links
  494.         else:
  495.             return links.get(b)
  496.  
  497.     def nodes(self):
  498.         """Return a list of nodes in the graph."""
  499.         return list(self.dict.keys())
  500.  
  501.  
  502. def UndirectedGraph(dict=None):
  503.     """Build a Graph where every edge (including future ones) goes both ways."""
  504.     return Graph(dict=dict, directed=False)
  505.  
  506.  
  507. def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
  508.                 curvature=lambda: random.uniform(1.1, 1.5)):
  509.     """Construct a random graph, with the specified nodes, and random links.
  510.    The nodes are laid out randomly on a (width x height) rectangle.
  511.    Then each node is connected to the min_links nearest neighbors.
  512.    Because inverse links are added, some nodes will have more connections.
  513.    The distance between nodes is the hypotenuse times curvature(),
  514.    where curvature() defaults to a random number between 1.1 and 1.5."""
  515.     g = UndirectedGraph()
  516.     g.locations = {}
  517.     # Build the cities
  518.     for node in nodes:
  519.         g.locations[node] = (random.randrange(width), random.randrange(height))
  520.     # Build roads from each city to at least min_links nearest neighbors.
  521.     for i in range(min_links):
  522.         for node in nodes:
  523.             if len(g.get(node)) < min_links:
  524.                 here = g.locations[node]
  525.  
  526.                 def distance_to_node(n):
  527.                     if n is node or g.get(node, n):
  528.                         return infinity
  529.                     return distance(g.locations[n], here)
  530.                 neighbor = argmin(nodes, key=distance_to_node)
  531.                 d = distance(g.locations[neighbor], here) * curvature()
  532.                 g.connect(node, neighbor, int(d))
  533.     return g
  534.  
  535.  
  536.    
  537. class GraphProblem(Problem):
  538.  
  539.     """The problem of searching a graph from one node to another."""
  540.  
  541.     def __init__(self, initial, goal, graph):
  542.         Problem.__init__(self, initial, goal)
  543.         self.graph = graph
  544.  
  545.     def actions(self, A):
  546.         """The actions at a graph node are just its neighbors."""
  547.         return list(self.graph.get(A).keys())
  548.  
  549.     def result(self, state, action):
  550.         """The result of going to a neighbor is just that neighbor."""
  551.         return action
  552.  
  553.     def path_cost(self, cost_so_far, A, action, B):
  554.         return cost_so_far + (self.graph.get(A, B) or infinity)
  555.  
  556.     def h(self, node):
  557.         """h function is straight-line distance from a node's state to goal."""
  558.         locs = getattr(self.graph, 'locations', None)
  559.         if locs:
  560.             return int(distance(locs[node.state], locs[self.goal]))
  561.         else:
  562.             return infinity
  563.            
  564.            
  565. #   Primer na definiranje na graf kako ekspliciten prostor na sostojbi vo koj ke se prebaruva
  566.  
  567. romania_map = UndirectedGraph(dict(
  568.     Arad=dict(Zerind=75, Sibiu=140, Timisoara=118),
  569.     Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211),
  570.     Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138),
  571.     Drobeta=dict(Mehadia=75),
  572.     Eforie=dict(Hirsova=86),
  573.     Fagaras=dict(Sibiu=99),
  574.     Hirsova=dict(Urziceni=98),
  575.     Iasi=dict(Vaslui=92, Neamt=87),
  576.     Lugoj=dict(Timisoara=111, Mehadia=70),
  577.     Oradea=dict(Zerind=71, Sibiu=151),
  578.     Pitesti=dict(Rimnicu=97),
  579.     Rimnicu=dict(Sibiu=80),
  580.     Urziceni=dict(Vaslui=142)))
  581.    
  582. #   Sledniot del ne e zadolzitelen da se definiranje
  583. #   Definicijata na klasata kako podrazbirana opcija za hevristicka funkcija koristi pravolinisko rastojanie
  584. #
  585. #   Dokolku slednite informacii ne gi definirate ili ne mozete da gi definirate treba da ja promenite definicijata
  586. #   na funkcijata "h" vo ramki na klasata GraphProblem taka da na soodveten nacin presmetate hevristicka funkcija
  587.  
  588.  
  589. romania_map.locations = dict(
  590.     Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288),
  591.     Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449),
  592.     Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506),
  593.     Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537),
  594.     Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410),
  595.     Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350),
  596.     Vaslui=(509, 444), Zerind=(108, 531))
  597.  
  598.    
  599. #   Primeri na povici so koi na primer moze da se izminuva grafot za gradovite vo Romanija
  600. #  
  601. #romania_problem = GraphProblem('Arad', 'Bucharest', romania_map)
  602. #  
  603. #answer1=breadth_first_tree_search(romania_problem)
  604. #print answer1.solve()
  605.  
  606. #answer2=breadth_first_graph_search(romania_problem)
  607. #print answer2.solve()
  608.  
  609. #answer3=uniform_cost_search(romania_problem)
  610. #print answer3.solve()
  611.  
  612. #answer4=astar_search(romania_problem)
  613. #print answer4.solve()
  614.  
  615. A=(2,1)
  616. B=(2,4)
  617. C=(2,10)
  618. D=(2,15)
  619. E=(2,19)
  620. F=(5,9)
  621. G=(4,11)
  622. H=(8,1)
  623. I=(8,5)
  624. J=(8,8)
  625. K=(8,13)
  626. L=(8,15)
  627. M=(8,19)
  628. ABdistance = distance(A,B)
  629. HIdistance = distance(H,I)
  630. BIdistance = distance(B,I)
  631. BCdistance = distance(B,C)
  632. IJdistance = distance(I,J)
  633. FCdistance = distance(F,C)
  634. GCdistance = distance(G,C)
  635. CDdistance = distance(C,D)
  636. FGdistance = distance(F,G)
  637. FJdistance = distance(F,J)
  638. KGdistance = distance(K,G)
  639. LKdistance = distance(L,K)
  640. DEdistance = distance(D,E)
  641. DLdistance = distance(D,L)
  642. LMdistance = distance(L,M)
  643. graph = UndirectedGraph({
  644.     "B": {"A": ABdistance, "I": BIdistance, "C": BCdistance},
  645.     "I": {"H": HIdistance, "J": IJdistance},
  646.     "C": {"F": FCdistance, "G": GCdistance, "D": CDdistance},
  647.     "F": {"G": FGdistance, "J": FJdistance},
  648.     "K": {"G": KGdistance, "L": LKdistance},
  649.     "D": {"E": DEdistance, "L": DLdistance},
  650.     "M": {"L": LMdistance}
  651. })
  652.  
  653.  
  654. graph.locations = dict(
  655. A = (2,1) , B = (2,4) , C = (2,10) ,
  656. D = (2,15) , E = (2,19) , F = (5,9) ,
  657. G = (4,11) , H = (8,1) , I = (8,5),
  658. J = (8,8) , K = (8,13) , L = (8,15),
  659. M = (8,19))
  660.  
  661. p1= GraphProblem(Pocetok,Stanica1, graph)
  662. p2= GraphProblem(Stanica1,Kraj,graph)
  663. r1= astar_search(p1)
  664. r2= astar_search(p2)
  665. cost1=r1.path_cost + r2.path_cost
  666. path1=list(Pocetok)+ r1.solution() +r2.solution()
  667.  
  668. p1= GraphProblem(Pocetok,Stanica2, graph)
  669. p2= GraphProblem(Stanica2,Kraj,graph)
  670. r1= astar_search(p1)
  671. r2= astar_search(p2)
  672. cost2=r1.path_cost + r2.path_cost
  673. path2=list(Pocetok)+ r1.solution() + r2.solution()
  674. if cost1 < cost2:
  675.     print(path1)
  676. elif cost1 > cost2:
  677.     print(path2)
  678. else:
  679.     print(path1)
  680.    
  681. ---------
  682. #Vtora
  683. Pocetok = input()
  684. Kraj = input()
  685. # Python modul vo koj se implementirani algoritmite za neinformirano i informirano prebaruvanje
  686.  
  687. # ______________________________________________________________________________________________
  688. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  689.  
  690. import sys
  691. import bisect
  692.  
  693. infinity = float('inf')  # sistemski definirana vrednost za beskonecnost
  694.  
  695.  
  696. # ______________________________________________________________________________________________
  697. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  698.  
  699. class Queue:
  700.     """Queue is an abstract class/interface. There are three types:
  701.        Stack(): A Last In First Out Queue.
  702.        FIFOQueue(): A First In First Out Queue.
  703.        PriorityQueue(order, f): Queue in sorted order (default min-first).
  704.    Each type supports the following methods and functions:
  705.        q.append(item)  -- add an item to the queue
  706.        q.extend(items) -- equivalent to: for item in items: q.append(item)
  707.        q.pop()         -- return the top item from the queue
  708.        len(q)          -- number of items in q (also q.__len())
  709.        item in q       -- does q contain item?
  710.    Note that isinstance(Stack(), Queue) is false, because we implement stacks
  711.    as lists.  If Python ever gets interfaces, Queue will be an interface."""
  712.  
  713.     def __init__(self):
  714.         raise NotImplementedError
  715.  
  716.     def extend(self, items):
  717.         for item in items:
  718.             self.append(item)
  719.  
  720.  
  721. def Stack():
  722.     """A Last-In-First-Out Queue."""
  723.     return []
  724.  
  725.  
  726. class FIFOQueue(Queue):
  727.     """A First-In-First-Out Queue."""
  728.  
  729.     def __init__(self):
  730.         self.A = []
  731.         self.start = 0
  732.  
  733.     def append(self, item):
  734.         self.A.append(item)
  735.  
  736.     def __len__(self):
  737.         return len(self.A) - self.start
  738.  
  739.     def extend(self, items):
  740.         self.A.extend(items)
  741.  
  742.     def pop(self):
  743.         e = self.A[self.start]
  744.         self.start += 1
  745.         if self.start > 5 and self.start > len(self.A) / 2:
  746.             self.A = self.A[self.start:]
  747.             self.start = 0
  748.         return e
  749.  
  750.     def __contains__(self, item):
  751.         return item in self.A[self.start:]
  752.  
  753.  
  754. class PriorityQueue(Queue):
  755.     """A queue in which the minimum (or maximum) element (as determined by f and
  756.    order) is returned first. If order is min, the item with minimum f(x) is
  757.    returned first; if order is max, then it is the item with maximum f(x).
  758.    Also supports dict-like lookup. This structure will be most useful in informed searches"""
  759.  
  760.     def __init__(self, order=min, f=lambda x: x):
  761.         self.A = []
  762.         self.order = order
  763.         self.f = f
  764.  
  765.     def append(self, item):
  766.         bisect.insort(self.A, (self.f(item), item))
  767.  
  768.     def __len__(self):
  769.         return len(self.A)
  770.  
  771.     def pop(self):
  772.         if self.order == min:
  773.             return self.A.pop(0)[1]
  774.         else:
  775.             return self.A.pop()[1]
  776.  
  777.     def __contains__(self, item):
  778.         return any(item == pair[1] for pair in self.A)
  779.  
  780.     def __getitem__(self, key):
  781.         for _, item in self.A:
  782.             if item == key:
  783.                 return item
  784.  
  785.     def __delitem__(self, key):
  786.         for i, (value, item) in enumerate(self.A):
  787.             if item == key:
  788.                 self.A.pop(i)
  789.  
  790.  
  791. # ______________________________________________________________________________________________
  792. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  793. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  794. # na sekoj eden problem sto sakame da go resime
  795.  
  796.  
  797. class Problem:
  798.     """The abstract class for a formal problem.  You should subclass this and
  799.    implement the method successor, and possibly __init__, goal_test, and
  800.    path_cost. Then you will create instances of your subclass and solve them
  801.    with the various search functions."""
  802.  
  803.     def __init__(self, initial, goal=None):
  804.         """The constructor specifies the initial state, and possibly a goal
  805.        state, if there is a unique goal.  Your subclass's constructor can add
  806.        other arguments."""
  807.         self.initial = initial
  808.         self.goal = goal
  809.  
  810.     def successor(self, state):
  811.         """Given a state, return a dictionary of {action : state} pairs reachable
  812.        from this state. If there are many successors, consider an iterator
  813.        that yields the successors one at a time, rather than building them
  814.        all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  815.         raise NotImplementedError
  816.  
  817.     def actions(self, state):
  818.         """Given a state, return a list of all actions possible from that state"""
  819.         raise NotImplementedError
  820.  
  821.     def result(self, state, action):
  822.         """Given a state and action, return the resulting state"""
  823.         raise NotImplementedError
  824.  
  825.     def goal_test(self, state):
  826.         """Return True if the state is a goal. The default method compares the
  827.        state to self.goal, as specified in the constructor. Implement this
  828.        method if checking against a single self.goal is not enough."""
  829.         return state == self.goal
  830.  
  831.     def path_cost(self, c, state1, action, state2):
  832.         """Return the cost of a solution path that arrives at state2 from
  833.        state1 via action, assuming cost c to get up to state1. If the problem
  834.        is such that the path doesn't matter, this function will only look at
  835.        state2.  If the path does matter, it will consider c and maybe state1
  836.        and action. The default method costs 1 for every step in the path."""
  837.         return c + 1
  838.  
  839.     def value(self):
  840.         """For optimization problems, each state has a value.  Hill-climbing
  841.        and related algorithms try to maximize this value."""
  842.         raise NotImplementedError
  843.  
  844.  
  845. # ______________________________________________________________________________
  846. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  847. # Klasata Node ne se nasleduva
  848.  
  849. class Node:
  850.     """A node in a search tree. Contains a pointer to the parent (the node
  851.    that this is a successor of) and to the actual state for this node. Note
  852.    that if a state is arrived at by two paths, then there are two nodes with
  853.    the same state.  Also includes the action that got us to this state, and
  854.    the total path_cost (also known as g) to reach the node.  Other functions
  855.    may add an f and h value; see best_first_graph_search and astar_search for
  856.    an explanation of how the f and h values are handled. You will not need to
  857.    subclass this class."""
  858.  
  859.     def __init__(self, state, parent=None, action=None, path_cost=0):
  860.         "Create a search tree Node, derived from a parent by an action."
  861.         self.state = state
  862.         self.parent = parent
  863.         self.action = action
  864.         self.path_cost = path_cost
  865.         self.depth = 0
  866.         if parent:
  867.             self.depth = parent.depth + 1
  868.  
  869.     def __repr__(self):
  870.         return "<Node %s>" % (self.state,)
  871.  
  872.     def __lt__(self, node):
  873.         return self.state < node.state
  874.  
  875.     def expand(self, problem):
  876.         "List the nodes reachable in one step from this node."
  877.         return [self.child_node(problem, action)
  878.                 for action in problem.actions(self.state)]
  879.  
  880.     def child_node(self, problem, action):
  881.         "Return a child node from this node"
  882.         next = problem.result(self.state, action)
  883.         return Node(next, self, action,
  884.                     problem.path_cost(self.path_cost, self.state,
  885.                                       action, next))
  886.  
  887.     def solution(self):
  888.         "Return the sequence of actions to go from the root to this node."
  889.         return [node.action for node in self.path()[1:]]
  890.  
  891.     def solve(self):
  892.         "Return the sequence of states to go from the root to this node."
  893.         return [node.state for node in self.path()[0:]]
  894.  
  895.     def path(self):
  896.         "Return a list of nodes forming the path from the root to this node."
  897.         x, result = self, []
  898.         while x:
  899.             result.append(x)
  900.             x = x.parent
  901.         return list(reversed(result))
  902.  
  903.     # We want for a queue of nodes in breadth_first_search or
  904.     # astar_search to have no duplicated states, so we treat nodes
  905.     # with the same state as equal. [Problem: this may not be what you
  906.     # want in other contexts.]
  907.  
  908.     def __eq__(self, other):
  909.         return isinstance(other, Node) and self.state == other.state
  910.  
  911.     def __hash__(self):
  912.         return hash(self.state)
  913.  
  914.  
  915. # ________________________________________________________________________________________________________
  916. #Neinformirano prebaruvanje vo ramki na drvo
  917. #Vo ramki na drvoto ne razresuvame jamki
  918.  
  919. def tree_search(problem, fringe):
  920.     """Search through the successors of a problem to find a goal.
  921.    The argument fringe should be an empty queue."""
  922.     fringe.append(Node(problem.initial))
  923.     while fringe:
  924.         node = fringe.pop()
  925.        
  926.         if problem.goal_test(node.state):
  927.             return node
  928.         fringe.extend(node.expand(problem))
  929.     return None
  930.  
  931.  
  932. def breadth_first_tree_search(problem):
  933.     "Search the shallowest nodes in the search tree first."
  934.     return tree_search(problem, FIFOQueue())
  935.  
  936.  
  937. def depth_first_tree_search(problem):
  938.     "Search the deepest nodes in the search tree first."
  939.     return tree_search(problem, Stack())
  940.  
  941.  
  942. # ________________________________________________________________________________________________________
  943. #Neinformirano prebaruvanje vo ramki na graf
  944. #Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  945.  
  946. def graph_search(problem, fringe):
  947.     """Search through the successors of a problem to find a goal.
  948.    The argument fringe should be an empty queue.
  949.    If two paths reach a state, only use the best one."""
  950.     closed = {}
  951.     fringe.append(Node(problem.initial))
  952.     while fringe:
  953.         node = fringe.pop()
  954.         if problem.goal_test(node.state):
  955.             return node
  956.         if node.state not in closed:
  957.             closed[node.state] = True
  958.             fringe.extend(node.expand(problem))
  959.     return None
  960.  
  961.  
  962. def breadth_first_graph_search(problem):
  963.     "Search the shallowest nodes in the search tree first."
  964.     return graph_search(problem, FIFOQueue())
  965.  
  966.  
  967. def depth_first_graph_search(problem):
  968.     "Search the deepest nodes in the search tree first."
  969.     return graph_search(problem, Stack())
  970.  
  971.  
  972. def uniform_cost_search(problem):
  973.     "Search the nodes in the search tree with lowest cost first."
  974.     return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  975.  
  976.  
  977. def depth_limited_search(problem, limit=50):
  978.     "depth first search with limited depth"
  979.  
  980.     def recursive_dls(node, problem, limit):
  981.         "helper function for depth limited"
  982.         cutoff_occurred = False
  983.         if problem.goal_test(node.state):
  984.             return node
  985.         elif node.depth == limit:
  986.             return 'cutoff'
  987.         else:
  988.             for successor in node.expand(problem):
  989.                 result = recursive_dls(successor, problem, limit)
  990.                 if result == 'cutoff':
  991.                     cutoff_occurred = True
  992.                 elif result != None:
  993.                     return result
  994.         if cutoff_occurred:
  995.             return 'cutoff'
  996.         else:
  997.             return None
  998.  
  999.     # Body of depth_limited_search:
  1000.     return recursive_dls(Node(problem.initial), problem, limit)
  1001.  
  1002.  
  1003. def iterative_deepening_search(problem):
  1004.  
  1005.     for depth in xrange(sys.maxint):
  1006.         result = depth_limited_search(problem, depth)
  1007.         if result is not 'cutoff':
  1008.             return result
  1009.  
  1010.        
  1011. # ________________________________________________________________________________________________________
  1012. #Pomosna funkcija za informirani prebaruvanja
  1013. #So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  1014.  
  1015. def memoize(fn, slot=None):
  1016.     """Memoize fn: make it remember the computed value for any argument list.
  1017.    If slot is specified, store result in that slot of first argument.
  1018.    If slot is false, store results in a dictionary."""
  1019.     if slot:
  1020.         def memoized_fn(obj, *args):
  1021.             if hasattr(obj, slot):
  1022.                 return getattr(obj, slot)
  1023.             else:
  1024.                 val = fn(obj, *args)
  1025.                 setattr(obj, slot, val)
  1026.                 return val
  1027.     else:
  1028.         def memoized_fn(*args):
  1029.             if not memoized_fn.cache.has_key(args):
  1030.                 memoized_fn.cache[args] = fn(*args)
  1031.             return memoized_fn.cache[args]
  1032.  
  1033.         memoized_fn.cache = {}
  1034.     return memoized_fn
  1035.  
  1036.  
  1037. # ________________________________________________________________________________________________________
  1038. #Informirano prebaruvanje vo ramki na graf
  1039.  
  1040. def best_first_graph_search(problem, f):
  1041.     """Search the nodes with the lowest f scores first.
  1042.    You specify the function f(node) that you want to minimize; for example,
  1043.    if f is a heuristic estimate to the goal, then we have greedy best
  1044.    first search; if f is node.depth then we have breadth-first search.
  1045.    There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  1046.    values will be cached on the nodes as they are computed. So after doing
  1047.    a best first search you can examine the f values of the path returned."""
  1048.  
  1049.     f = memoize(f, 'f')
  1050.     node = Node(problem.initial)
  1051.     if problem.goal_test(node.state):
  1052.         return node
  1053.     frontier = PriorityQueue(min, f)
  1054.     frontier.append(node)
  1055.     explored = set()
  1056.     while frontier:
  1057.         node = frontier.pop()
  1058.         if problem.goal_test(node.state):
  1059.             return node
  1060.         explored.add(node.state)
  1061.         for child in node.expand(problem):
  1062.             if child.state not in explored and child not in frontier:
  1063.                 frontier.append(child)
  1064.             elif child in frontier:
  1065.                 incumbent = frontier[child]
  1066.                 if f(child) < f(incumbent):
  1067.                     del frontier[incumbent]
  1068.                     frontier.append(child)
  1069.     return None
  1070.  
  1071.  
  1072. def greedy_best_first_graph_search(problem, h=None):
  1073.     "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  1074.     h = memoize(h or problem.h, 'h')
  1075.     return best_first_graph_search(problem, h)
  1076.  
  1077.  
  1078. def astar_search(problem, h=None):
  1079.     "A* search is best-first graph search with f(n) = g(n)+h(n)."
  1080.     h = memoize(h or problem.h, 'h')
  1081.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  1082.  
  1083.  
  1084. # ________________________________________________________________________________________________________
  1085. #Dopolnitelni prebaruvanja
  1086. #Recursive_best_first_search e implementiran
  1087. #Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  1088.  
  1089. def recursive_best_first_search(problem, h=None):
  1090.     h = memoize(h or problem.h, 'h')
  1091.  
  1092.     def RBFS(problem, node, flimit):
  1093.         if problem.goal_test(node.state):
  1094.             return node, 0  # (The second value is immaterial)
  1095.         successors = node.expand(problem)
  1096.         if len(successors) == 0:
  1097.             return None, infinity
  1098.         for s in successors:
  1099.             s.f = max(s.path_cost + h(s), node.f)
  1100.         while True:
  1101.             # Order by lowest f value
  1102.             successors.sort(key=lambda x: x.f)
  1103.             best = successors[0]
  1104.             if best.f > flimit:
  1105.                 return None, best.f
  1106.             if len(successors) > 1:
  1107.                 alternative = successors[1].f
  1108.             else:
  1109.                 alternative = infinity
  1110.             result, best.f = RBFS(problem, best, min(flimit, alternative))
  1111.             if result is not None:
  1112.                 return result, best.f
  1113.  
  1114.     node = Node(problem.initial)
  1115.     node.f = h(node)
  1116.     result, bestf = RBFS(problem, node, infinity)
  1117.     return result
  1118.  
  1119.  
  1120. # Graphs and Graph Problems
  1121. import math
  1122.  
  1123. def distance(a, b):
  1124.     """The distance between two (x, y) points."""
  1125.     return math.hypot((a[0] - b[0]), (a[1] - b[1]))
  1126.    
  1127.    
  1128. class Graph:
  1129.  
  1130.     """A graph connects nodes (verticies) by edges (links).  Each edge can also
  1131.    have a length associated with it.  The constructor call is something like:
  1132.        g = Graph({'A': {'B': 1, 'C': 2})
  1133.    this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from
  1134.    A to B,  and an edge of length 2 from A to C.  You can also do:
  1135.        g = Graph({'A': {'B': 1, 'C': 2}, directed=False)
  1136.    This makes an undirected graph, so inverse links are also added. The graph
  1137.    stays undirected; if you add more links with g.connect('B', 'C', 3), then
  1138.    inverse link is also added.  You can use g.nodes() to get a list of nodes,
  1139.    g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the
  1140.    length of the link from A to B.  'Lengths' can actually be any object at
  1141.    all, and nodes can be any hashable object."""
  1142.  
  1143.     def __init__(self, dict=None, directed=True):
  1144.         self.dict = dict or {}
  1145.         self.directed = directed
  1146.         if not directed:
  1147.             self.make_undirected()
  1148.  
  1149.     def make_undirected(self):
  1150.         """Make a digraph into an undirected graph by adding symmetric edges."""
  1151.         for a in list(self.dict.keys()):
  1152.             for (b, dist) in self.dict[a].items():
  1153.                 self.connect1(b, a, dist)
  1154.  
  1155.     def connect(self, A, B, distance=1):
  1156.         """Add a link from A and B of given distance, and also add the inverse
  1157.        link if the graph is undirected."""
  1158.         self.connect1(A, B, distance)
  1159.         if not self.directed:
  1160.             self.connect1(B, A, distance)
  1161.  
  1162.     def connect1(self, A, B, distance):
  1163.         """Add a link from A to B of given distance, in one direction only."""
  1164.         self.dict.setdefault(A, {})[B] = distance
  1165.  
  1166.     def get(self, a, b=None):
  1167.         """Return a link distance or a dict of {node: distance} entries.
  1168.        .get(a,b) returns the distance or None;
  1169.        .get(a) returns a dict of {node: distance} entries, possibly {}."""
  1170.         links = self.dict.setdefault(a, {})
  1171.         if b is None:
  1172.             return links
  1173.         else:
  1174.             return links.get(b)
  1175.  
  1176.     def nodes(self):
  1177.         """Return a list of nodes in the graph."""
  1178.         return list(self.dict.keys())
  1179.  
  1180.  
  1181. def UndirectedGraph(dict=None):
  1182.     """Build a Graph where every edge (including future ones) goes both ways."""
  1183.     return Graph(dict=dict, directed=False)
  1184.  
  1185.  
  1186. def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
  1187.                 curvature=lambda: random.uniform(1.1, 1.5)):
  1188.     """Construct a random graph, with the specified nodes, and random links.
  1189.    The nodes are laid out randomly on a (width x height) rectangle.
  1190.    Then each node is connected to the min_links nearest neighbors.
  1191.    Because inverse links are added, some nodes will have more connections.
  1192.    The distance between nodes is the hypotenuse times curvature(),
  1193.    where curvature() defaults to a random number between 1.1 and 1.5."""
  1194.     g = UndirectedGraph()
  1195.     g.locations = {}
  1196.     # Build the cities
  1197.     for node in nodes:
  1198.         g.locations[node] = (random.randrange(width), random.randrange(height))
  1199.     # Build roads from each city to at least min_links nearest neighbors.
  1200.     for i in range(min_links):
  1201.         for node in nodes:
  1202.             if len(g.get(node)) < min_links:
  1203.                 here = g.locations[node]
  1204.  
  1205.                 def distance_to_node(n):
  1206.                     if n is node or g.get(node, n):
  1207.                         return infinity
  1208.                     return distance(g.locations[n], here)
  1209.                 neighbor = argmin(nodes, key=distance_to_node)
  1210.                 d = distance(g.locations[neighbor], here) * curvature()
  1211.                 g.connect(node, neighbor, int(d))
  1212.     return g
  1213.  
  1214.  
  1215.    
  1216. class GraphProblem(Problem):
  1217.  
  1218.     """The problem of searching a graph from one node to another."""
  1219.  
  1220.     def __init__(self, initial, goal, graph):
  1221.         Problem.__init__(self, initial, goal)
  1222.         self.graph = graph
  1223.  
  1224.     def actions(self, A):
  1225.         """The actions at a graph node are just its neighbors."""
  1226.         return list(self.graph.get(A).keys())
  1227.  
  1228.     def result(self, state, action):
  1229.         """The result of going to a neighbor is just that neighbor."""
  1230.         return action
  1231.  
  1232.     def path_cost(self, cost_so_far, A, action, B):
  1233.         return cost_so_far + (self.graph.get(A, B) or infinity)
  1234.  
  1235.     def h(self, node):
  1236.         """h function is straight-line distance from a node's state to goal."""
  1237.         locs = getattr(self.graph, 'locations', None)
  1238.         if locs:
  1239.             return int(distance(locs[node.state], locs[self.goal]))
  1240.         else:
  1241.             return infinity
  1242.            
  1243.            
  1244. #   Primer na definiranje na graf kako ekspliciten prostor na sostojbi vo koj ke se prebaruva
  1245.  
  1246. romania_map = UndirectedGraph(dict(
  1247.     Arad=dict(Zerind=75, Sibiu=140, Timisoara=118),
  1248.     Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211),
  1249.     Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138),
  1250.     Drobeta=dict(Mehadia=75),
  1251.     Eforie=dict(Hirsova=86),
  1252.     Fagaras=dict(Sibiu=99),
  1253.     Hirsova=dict(Urziceni=98),
  1254.     Iasi=dict(Vaslui=92, Neamt=87),
  1255.     Lugoj=dict(Timisoara=111, Mehadia=70),
  1256.     Oradea=dict(Zerind=71, Sibiu=151),
  1257.     Pitesti=dict(Rimnicu=97),
  1258.     Rimnicu=dict(Sibiu=80),
  1259.     Urziceni=dict(Vaslui=142)))
  1260.    
  1261. #   Sledniot del ne e zadolzitelen da se definiranje
  1262. #   Definicijata na klasata kako podrazbirana opcija za hevristicka funkcija koristi pravolinisko rastojanie
  1263. #
  1264. #   Dokolku slednite informacii ne gi definirate ili ne mozete da gi definirate treba da ja promenite definicijata
  1265. #   na funkcijata "h" vo ramki na klasata GraphProblem taka da na soodveten nacin presmetate hevristicka funkcija
  1266.  
  1267.  
  1268. romania_map.locations = dict(
  1269.     Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288),
  1270.     Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449),
  1271.     Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506),
  1272.     Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537),
  1273.     Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410),
  1274.     Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350),
  1275.     Vaslui=(509, 444), Zerind=(108, 531))
  1276.  
  1277.    
  1278. #   Primeri na povici so koi na primer moze da se izminuva grafot za gradovite vo Romanija
  1279. #  
  1280. #romania_problem = GraphProblem('Arad', 'Bucharest', romania_map)
  1281. #  
  1282. #answer1=breadth_first_tree_search(romania_problem)
  1283. #print answer1.solve()
  1284.  
  1285. #answer2=breadth_first_graph_search(romania_problem)
  1286. #print answer2.solve()
  1287.  
  1288. #answer3=uniform_cost_search(romania_problem)
  1289. #print answer3.solve()
  1290.  
  1291. #answer4=astar_search(romania_problem)
  1292. #print answer4.solve()
  1293.  
  1294.  
  1295.  
  1296. class GraphProblem(Problem):
  1297.     """The problem of searching a graph from one node to another."""
  1298.  
  1299.     def __init__(self, initial, goal, graph):
  1300.         Problem.__init__(self, initial, goal)
  1301.         self.graph = graph
  1302.  
  1303.     def actions(self, A):
  1304.         """The actions at a graph node are just its neighbors."""
  1305.         return list(self.graph.get(A).keys())
  1306.  
  1307.     def result(self, state, action):
  1308.         """The result of going to a neighbor is just that neighbor."""
  1309.         return action
  1310.  
  1311.     def path_cost(self, cost_so_far, A, action, B):
  1312.         return cost_so_far + (self.graph.get(A, B) or infinity)
  1313.  
  1314.     def h(self, node):
  1315.         """h function is straight-line distance from a node's state to goal."""
  1316.         prob = GraphProblem(node.state, self.goal, self.graph)
  1317.         temp = breadth_first_graph_search(prob).solve()
  1318.         passedTowns = len(temp) - 1
  1319.         return passedTowns
  1320.  
  1321.  
  1322. graph = UndirectedGraph(dict(
  1323.     Frankfurt=dict(Mannheim=85, Wurzburg=217, Kassel=173),
  1324.     Kassel=dict(Munchen=502),
  1325.     Munchen=dict(Nurnberg=167, Augsburg=84),
  1326.     Augsburg=dict(Karlsruhe=250),
  1327.     Karlsruhe=dict(Mannheim=80),
  1328.     Wurzburg=dict(Erfurt=186, Nurnberg=103),
  1329.     Nurnberg=dict(Stuttgart=183)
  1330. ))
  1331.  
  1332. graph_problem = GraphProblem(Pocetok, Kraj, graph)
  1333. answer = astar_search(graph_problem).path_cost
  1334. print(answer)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement