Advertisement
fensa08

#VI LAB4/1

May 7th, 2019
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 27.97 KB | None | 0 0
  1. #VI LAB4/1 made by Fensa08
  2. Граф Problem 1 (0 / 0)
  3.  
  4. На сликата е даден просторот на состојби на некој проблем, претставен како граф.
  5.  
  6. enter image description here
  7.  
  8. Јазлите во просторот на состојби ги имаат следните локации:
  9.  
  10. A (2,1) ; B (2,4) ; C (2,10)
  11.  
  12. D (2,15) ; E (2,19) ; F (5,9)
  13.  
  14. G (4,11) ; H (8,1) ; I (8,5)
  15.  
  16. J (8,8) ; K (8,13) ; L (8,15)
  17.  
  18. M (8,19)
  19.  
  20. Во рамки на почетниот код имате почетна дефиниција за дадениот граф. Забележете дека должините на ребрата во графот се дадени како променливи. Вредностите кои ќе ги добијат овие променливи треба да ги определите самите. При определувањето на должината на ребрата да не се прави целобројно заокружување на резултатот.
  21.  
  22. Треба да го решите проблемот на наоѓање на најкратката патека во графот (секвенца од јазли кои се посетуваат) од даден почетен до даден краен јазел, меѓутоа патеката задолжително мора да посети само една попатна станица од двете кои исто така ви се дадени.
  23.  
  24. Појаснување: Постојат две можни најкратки патеки, едната поминува низ првата, а втората поминува низ втората попатна станица. Вие треба од двете да ја вратите пократката. Ако двете патеки се со иста должина да се врати патеката која поминува низ првата попатна станица (Stanica1).
  25.  
  26. За секој тест пример се менуваат почетниот и крајниот јазел како и двете попатни станици. Во рамки на почетниот код даден за задачата се вчитуваат влезните аргументи за секој тест пример. Во променливите Pocetok и Kraj ги имате почетниот и крајниот јазел за најкратката патека која треба да ја најдете, а во променливите Stanica1 и Stanica2 ги имате двете можни попатни станици од кои мора да се посети точно една.
  27.  
  28. Вашиот код треба да има само еден повик на функција за приказ на стандарден излез (print) со кој ќе ја вратите најкратката патека помеѓу почетниот и крајниот јазел со посетена само една попатна станица.
  29.  
  30. ####################################################################################################################################
  31.  
  32.  
  33. from sys import maxsize as infinity
  34.  
  35.  
  36.  
  37. """
  38. Информирано пребарување во рамки на граф
  39. """
  40.  
  41.  
  42. def memoize(fn, slot=None):
  43.     """ Запамети ја пресметаната вредност за која била листа од
  44.    аргументи. Ако е специфициран slot, зачувај го резултатот во
  45.    тој slot на првиот аргумент. Ако slot е None, зачувај ги
  46.    резултатите во речник.
  47.  
  48.    :param fn: зададена функција
  49.    :param slot: име на атрибут во кој се чуваат резултатите од функцијата
  50.    :return: функција со модификација за зачувување на резултатите
  51.    """
  52.     if slot:
  53.         def memoized_fn(obj, *args):
  54.             if hasattr(obj, slot):
  55.                 return getattr(obj, slot)
  56.             else:
  57.                 val = fn(obj, *args)
  58.                 setattr(obj, slot, val)
  59.                 return val
  60.     else:
  61.         def memoized_fn(*args):
  62.             if args not in memoized_fn.cache:
  63.                 memoized_fn.cache[args] = fn(*args)
  64.             return memoized_fn.cache[args]
  65.  
  66.         memoized_fn.cache = {}
  67.     return memoized_fn
  68.  
  69.  
  70. def best_first_graph_search(problem, f):
  71.     """Пребарувај низ следбениците на даден проблем за да најдеш цел. Користи
  72.     функција за евалуација за да се одлучи кој е сосед најмногу ветува и
  73.     потоа да се истражи. Ако до дадена состојба стигнат два пата, употреби
  74.     го најдобриот пат.
  75.  
  76.    :param problem: даден проблем
  77.    :param f: дадена функција за евристика
  78.    :return: Node or None
  79.    """
  80.     f = memoize(f, 'f')
  81.     node = Node(problem.initial)
  82.     if problem.goal_test(node.state):
  83.         return node
  84.     frontier = PriorityQueue(min, f)
  85.     frontier.append(node)
  86.     explored = set()
  87.     while frontier:
  88.         node = frontier.pop()
  89.         if problem.goal_test(node.state):
  90.             return node
  91.         explored.add(node.state)
  92.         for child in node.expand(problem):
  93.             if child.state not in explored and child not in frontier:
  94.                 frontier.append(child)
  95.             elif child in frontier:
  96.                 incumbent = frontier[child]
  97.                 if f(child) < f(incumbent):
  98.                     del frontier[incumbent]
  99.                     frontier.append(child)
  100.     return None
  101.  
  102.  
  103. def greedy_best_first_graph_search(problem, h=None):
  104.     """ Greedy best-first пребарување се остварува ако се специфицира дека f(n) = h(n).
  105.  
  106.    :param problem: даден проблем
  107.    :param h: дадена функција за евристика
  108.    :return: Node or None
  109.    """
  110.     h = memoize(h or problem.h, 'h')
  111.     return best_first_graph_search(problem, h)
  112.  
  113.  
  114. def astar_search(problem, h=None):
  115.     """ A* пребарување е best-first graph пребарување каде f(n) = g(n) + h(n).
  116.  
  117.    :param problem: даден проблем
  118.    :param h: дадена функција за евристика
  119.    :return: Node or None
  120.    """
  121.     h = memoize(h or problem.h, 'h')
  122.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  123.  
  124.  
  125. def recursive_best_first_search(problem, h=None):
  126.     """Recursive best first search - ја ограничува рекурзијата
  127.     преку следење на f-вредноста на најдобриот алтернативен пат
  128.     од било кој јазел предок (еден чекор гледање нанапред).
  129.  
  130.    :param problem: даден проблем
  131.    :param h: дадена функција за евристика
  132.    :return: Node or None
  133.    """
  134.     h = memoize(h or problem.h, 'h')
  135.  
  136.     def RBFS(problem, node, flimit):
  137.         if problem.goal_test(node.state):
  138.             return node, 0  # (втората вредност е неважна)
  139.         successors = node.expand(problem)
  140.         if len(successors) == 0:
  141.             return None, infinity
  142.         for s in successors:
  143.             s.f = max(s.path_cost + h(s), node.f)
  144.         while True:
  145.             # Подреди ги според најниската f вредност
  146.             successors.sort(key=lambda x: x.f)
  147.             best = successors[0]
  148.             if best.f > flimit:
  149.                 return None, best.f
  150.             if len(successors) > 1:
  151.                 alternative = successors[1].f
  152.             else:
  153.                 alternative = infinity
  154.             result, best.f = RBFS(problem, best, min(flimit, alternative))
  155.             if result is not None:
  156.                 return result, best.f
  157.  
  158.     node = Node(problem.initial)
  159.     node.f = h(node)
  160.     result, bestf = RBFS(problem, node, infinity)
  161.     return result
  162.  
  163.  
  164.  
  165. import math
  166. import random
  167.  
  168. import bisect
  169.  
  170.  
  171. """
  172. Дефинирање на класа за структурата на проблемот кој ќе го решаваме со пребарување.
  173. Класата Problem е апстрактна класа од која правиме наследување за дефинирање на основните
  174. карактеристики на секој проблем што сакаме да го решиме
  175. """
  176.  
  177.  
  178. class Problem:
  179.     def __init__(self, initial, goal=None):
  180.         self.initial = initial
  181.         self.goal = goal
  182.  
  183.     def successor(self, state):
  184.         """За дадена состојба, врати речник од парови {акција : состојба}
  185.        достапни од оваа состојба. Ако има многу следбеници, употребете
  186.        итератор кој би ги генерирал следбениците еден по еден, наместо да
  187.        ги генерирате сите одеднаш.
  188.  
  189.        :param state: дадена состојба
  190.        :return:  речник од парови {акција : состојба} достапни од оваа
  191.                  состојба
  192.        :rtype: dict
  193.        """
  194.         raise NotImplementedError
  195.  
  196.     def actions(self, state):
  197.         """За дадена состојба state, врати листа од сите акции што може да
  198.        се применат над таа состојба
  199.  
  200.        :param state: дадена состојба
  201.        :return: листа на акции
  202.        :rtype: list
  203.        """
  204.         return self.successor(state).keys()
  205.  
  206.     def result(self, state, action):
  207.         """За дадена состојба state и акција action, врати ја состојбата
  208.        што се добива со примена на акцијата над состојбата
  209.  
  210.        :param state: дадена состојба
  211.        :param action: дадена акција
  212.        :return: резултантна состојба
  213.        """
  214.         possible = self.successor(state)
  215.         return possible[action]
  216.  
  217.  
  218.     def goal_test(self, state):
  219.         """Врати True ако state е целна состојба. Даденава имплементација
  220.        на методот директно ја споредува state со self.goal, како што е
  221.        специфицирана во конструкторот. Имплементирајте го овој метод ако
  222.        проверката со една целна состојба self.goal не е доволна.
  223.  
  224.        :param state: дадена состојба
  225.        :return: дали дадената состојба е целна состојба
  226.        :rtype: bool
  227.        """
  228.         return state == self.goal
  229.  
  230.     def path_cost(self, c, state1, action, state2):
  231.         """Врати ја цената на решавачкиот пат кој пристигнува во состојбата
  232.        state2 од состојбата state1 преку акцијата action, претпоставувајќи
  233.        дека цената на патот до состојбата state1 е c. Ако проблемот е таков
  234.        што патот не е важен, оваа функција ќе ја разгледува само состојбата
  235.        state2. Ако патот е важен, ќе ја разгледува цената c и можеби и
  236.        state1 и action. Даденава имплементација му доделува цена 1 на секој
  237.        чекор од патот.
  238.  
  239.        :param c: цена на патот до состојбата state1
  240.        :param state1: дадена моментална состојба
  241.        :param action: акција која треба да се изврши
  242.        :param state2: состојба во која треба да се стигне
  243.        :return: цена на патот по извршување на акцијата
  244.        :rtype: float
  245.        """
  246.         return c + 1
  247.  
  248.     def value(self):
  249.         """За проблеми на оптимизација, секоја состојба си има вредност.
  250.        Hill-climbing и сличните алгоритми се обидуваат да ја максимизираат
  251.        оваа вредност.
  252.  
  253.        :return: вредност на состојба
  254.        :rtype: float
  255.        """
  256.         raise NotImplementedError
  257.  
  258.  
  259. """
  260. Дефинирање на класата за структурата на јазел од пребарување.
  261. Класата Node не се наследува
  262. """
  263.  
  264.  
  265. class Node:
  266.     def __init__(self, state, parent=None, action=None, path_cost=0):
  267.         """Креирај јазол од пребарувачкото дрво, добиен од parent со примена
  268.        на акцијата action
  269.  
  270.        :param state: моментална состојба (current state)
  271.        :param parent: родителска состојба (parent state)
  272.        :param action: акција (action)
  273.        :param path_cost: цена на патот (path cost)
  274.        """
  275.         self.state = state
  276.         self.parent = parent
  277.         self.action = action
  278.         self.path_cost = path_cost
  279.         self.depth = 0  # search depth
  280.         if parent:
  281.             self.depth = parent.depth + 1
  282.  
  283.     def __repr__(self):
  284.         return "<Node %s>" % (self.state,)
  285.  
  286.     def __lt__(self, node):
  287.         return self.state < node.state
  288.  
  289.     def expand(self, problem):
  290.         """Излистај ги јазлите достапни во еден чекор од овој јазол.
  291.  
  292.        :param problem: даден проблем
  293.        :return: листа на достапни јазли во еден чекор
  294.        :rtype: list(Node)
  295.        """
  296.         return [self.child_node(problem, action)
  297.                 for action in problem.actions(self.state)]
  298.  
  299.     def child_node(self, problem, action):
  300.         """Дете јазел
  301.  
  302.        :param problem: даден проблем
  303.        :param action: дадена акција
  304.        :return: достапен јазел според дадената акција
  305.        :rtype: Node
  306.        """
  307.         next_state = problem.result(self.state, action)
  308.         return Node(next_state, self, action,
  309.                     problem.path_cost(self.path_cost, self.state,
  310.                                       action, next_state))
  311.  
  312.     def solution(self):
  313.         """Врати ја секвенцата од акции за да се стигне од коренот до овој јазол.
  314.  
  315.        :return: секвенцата од акции
  316.        :rtype: list
  317.        """
  318.         return [node.action for node in self.path()[1:]]
  319.  
  320.     def solve(self):
  321.         """Врати ја секвенцата од состојби за да се стигне од коренот до овој јазол.
  322.  
  323.        :return: листа од состојби
  324.        :rtype: list
  325.        """
  326.         return [node.state for node in self.path()[0:]]
  327.  
  328.     def path(self):
  329.         """Врати ја листата од јазли што го формираат патот од коренот до овој јазол.
  330.  
  331.        :return: листа од јазли од патот
  332.        :rtype: list(Node)
  333.        """
  334.         x, result = self, []
  335.         while x:
  336.             result.append(x)
  337.             x = x.parent
  338.         result.reverse()
  339.         return result
  340.  
  341.     """Сакаме редицата од јазли кај breadth_first_search или
  342.    astar_search да не содржи состојби - дупликати, па јазлите што
  343.    содржат иста состојба ги третираме како исти. [Проблем: ова може
  344.    да не биде пожелно во други ситуации.]"""
  345.  
  346.     def __eq__(self, other):
  347.         return isinstance(other, Node) and self.state == other.state
  348.  
  349.     def __hash__(self):
  350.         return hash(self.state)
  351.  
  352.  
  353. """
  354. Дефинирање на помошни структури за чување на листата на генерирани, но непроверени јазли
  355. """
  356.  
  357.  
  358. class Queue:
  359.     """Queue е апстрактна класа / интерфејс. Постојат 3 типа:
  360.        Stack(): Last In First Out Queue (стек).
  361.        FIFOQueue(): First In First Out Queue (редица).
  362.        PriorityQueue(order, f): Queue во сортиран редослед (подразбирливо,од најмалиот кон
  363.                                 најголемиот јазол).
  364.    """
  365.  
  366.     def __init__(self):
  367.         raise NotImplementedError
  368.  
  369.     def append(self, item):
  370.         """Додади го елементот item во редицата
  371.  
  372.        :param item: даден елемент
  373.        :return: None
  374.        """
  375.         raise NotImplementedError
  376.  
  377.     def extend(self, items):
  378.         """Додади ги елементите items во редицата
  379.  
  380.        :param items: дадени елементи
  381.        :return: None
  382.        """
  383.         raise NotImplementedError
  384.  
  385.     def pop(self):
  386.         """Врати го првиот елемент од редицата
  387.  
  388.        :return: прв елемент
  389.        """
  390.         raise NotImplementedError
  391.  
  392.     def __len__(self):
  393.         """Врати го бројот на елементи во редицата
  394.  
  395.        :return: број на елементи во редицата
  396.        :rtype: int
  397.        """
  398.         raise NotImplementedError
  399.  
  400.     def __contains__(self, item):
  401.         """Проверка дали редицата го содржи елементот item
  402.  
  403.        :param item: даден елемент
  404.        :return: дали queue го содржи item
  405.        :rtype: bool
  406.        """
  407.         raise NotImplementedError
  408.  
  409.  
  410. class Stack(Queue):
  411.     """Last-In-First-Out Queue."""
  412.  
  413.     def __init__(self):
  414.         self.data = []
  415.  
  416.     def append(self, item):
  417.         self.data.append(item)
  418.  
  419.     def extend(self, items):
  420.         self.data.extend(items)
  421.  
  422.     def pop(self):
  423.         return self.data.pop()
  424.  
  425.     def __len__(self):
  426.         return len(self.data)
  427.  
  428.     def __contains__(self, item):
  429.         return item in self.data
  430.  
  431.  
  432. class FIFOQueue(Queue):
  433.     """First-In-First-Out Queue."""
  434.  
  435.     def __init__(self):
  436.         self.data = []
  437.  
  438.     def append(self, item):
  439.         self.data.append(item)
  440.  
  441.     def extend(self, items):
  442.         self.data.extend(items)
  443.  
  444.     def pop(self):
  445.         return self.data.pop(0)
  446.  
  447.     def __len__(self):
  448.         return len(self.data)
  449.  
  450.     def __contains__(self, item):
  451.         return item in self.data
  452.  
  453.  
  454. class PriorityQueue(Queue):
  455.     """Редица во која прво се враќа минималниот (или максималниот) елемент
  456.    (како што е определено со f и order). Оваа структура се користи кај
  457.    информирано пребарување"""
  458.     """"""
  459.  
  460.     def __init__(self, order=min, f=lambda x: x):
  461.         """
  462.        :param order: функција за подредување, ако order е min, се враќа елементот
  463.                      со минимална f(x); ако order е max, тогаш се враќа елементот
  464.                      со максимална f(x).
  465.        :param f: функција f(x)
  466.        """
  467.         assert order in [min, max]
  468.         self.data = []
  469.         self.order = order
  470.         self.f = f
  471.  
  472.     def append(self, item):
  473.         bisect.insort_right(self.data, (self.f(item), item))
  474.  
  475.     def extend(self, items):
  476.         for item in items:
  477.             bisect.insort_right(self.data, (self.f(item), item))
  478.  
  479.     def pop(self):
  480.         if self.order == min:
  481.             return self.data.pop(0)[1]
  482.         return self.data.pop()[1]
  483.  
  484.     def __len__(self):
  485.         return len(self.data)
  486.  
  487.     def __contains__(self, item):
  488.         return any(item == pair[1] for pair in self.data)
  489.  
  490.     def __getitem__(self, key):
  491.         for _, item in self.data:
  492.             if item == key:
  493.                 return item
  494.  
  495.     def __delitem__(self, key):
  496.         for i, (value, item) in enumerate(self.data):
  497.             if item == key:
  498.                 self.data.pop(i)
  499.  
  500.  
  501.  
  502. def distance(a, b):
  503.     """The distance between two (x, y) points."""
  504.     return math.hypot((a[0] - b[0]), (a[1] - b[1]))
  505.  
  506.  
  507. class Graph:
  508.     """A graph connects nodes (verticies) by edges (links).  Each edge can also
  509.    have a length associated with it.  The constructor call is something like:
  510.        g = Graph({'A': {'B': 1, 'C': 2})
  511.    this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from
  512.    A to B,  and an edge of length 2 from A to C.  You can also do:
  513.        g = Graph({'A': {'B': 1, 'C': 2}, directed=False)
  514.    This makes an undirected graph, so inverse links are also added. The graph
  515.    stays undirected; if you add more links with g.connect('B', 'C', 3), then
  516.    inverse link is also added.  You can use g.nodes() to get a list of nodes,
  517.    g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the
  518.    length of the link from A to B.  'Lengths' can actually be any object at
  519.    all, and nodes can be any hashable object."""
  520.  
  521.     def __init__(self, dictionary=None, directed=True):
  522.         self.dict = dictionary or {}
  523.         self.directed = directed
  524.         if not directed:
  525.             self.make_undirected()
  526.  
  527.     def make_undirected(self):
  528.         """Make a digraph into an undirected graph by adding symmetric edges."""
  529.         for a in list(self.dict.keys()):
  530.             for (b, dist) in self.dict[a].items():
  531.                 self.connect1(b, a, dist)
  532.  
  533.     def connect(self, node_a, node_b, distance_val=1):
  534.         """Add a link from node_a and node_b of given distance_val, and also add the inverse
  535.        link if the graph is undirected."""
  536.         self.connect1(node_a, node_b, distance_val)
  537.         if not self.directed:
  538.             self.connect1(node_b, node_a, distance_val)
  539.  
  540.     def connect1(self, node_a, node_b, distance_val):
  541.         """Add a link from node_a to node_b of given distance_val, in one direction only."""
  542.         self.dict.setdefault(node_a, {})[node_b] = distance_val
  543.  
  544.     def get(self, a, b=None):
  545.         """Return a link distance or a dict of {node: distance} entries.
  546.        .get(a,b) returns the distance or None;
  547.        .get(a) returns a dict of {node: distance} entries, possibly {}."""
  548.         links = self.dict.setdefault(a, {})
  549.         if b is None:
  550.             return links
  551.         else:
  552.             return links.get(b)
  553.  
  554.     def nodes(self):
  555.         """Return a list of nodes in the graph."""
  556.         return list(self.dict.keys())
  557.  
  558.  
  559. def UndirectedGraph(dictionary=None):
  560.     """Build a Graph where every edge (including future ones) goes both ways."""
  561.     return Graph(dictionary=dictionary, directed=False)
  562.  
  563.  
  564. def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
  565.                 curvature=lambda: random.uniform(1.1, 1.5)):
  566.     """Construct a random graph, with the specified nodes, and random links.
  567.    The nodes are laid out randomly on a (width x height) rectangle.
  568.    Then each node is connected to the min_links nearest neighbors.
  569.    Because inverse links are added, some nodes will have more connections.
  570.    The distance between nodes is the hypotenuse times curvature(),
  571.    where curvature() defaults to a random number between 1.1 and 1.5."""
  572.     g = UndirectedGraph()
  573.     g.locations = {}
  574.     # Build the cities
  575.     for node in nodes:
  576.         g.locations[node] = (random.randrange(width), random.randrange(height))
  577.     # Build roads from each city to at least min_links nearest neighbors.
  578.     for i in range(min_links):
  579.         for node in nodes:
  580.             if len(g.get(node)) < min_links:
  581.                 here = g.locations[node]
  582.  
  583.                 def distance_to_node(n):
  584.                     if n is node or g.get(node, n):
  585.                         return math.inf
  586.                     return distance(g.locations[n], here)
  587.  
  588.                 neighbor = nodes.index(min(nodes, key=distance_to_node))
  589.                 d = distance(g.locations[neighbor], here) * curvature()
  590.                 g.connect(node, neighbor, int(d))
  591.     return g
  592.  
  593.  
  594. class GraphProblem(Problem):
  595.     """The problem of searching a graph from one node to another."""
  596.  
  597.     def __init__(self, initial, goal, graph):
  598.         super().__init__(initial, goal)
  599.         self.graph = graph
  600.  
  601.     def actions(self, state):
  602.         """The actions at a graph node are just its neighbors."""
  603.         return list(self.graph.get(state).keys())
  604.  
  605.     def result(self, state, action):
  606.         """The result of going to a neighbor is just that neighbor."""
  607.         return action
  608.  
  609.     def path_cost(self, c, state1, action, state2):
  610.         return c + (self.graph.get(state1, state2) or math.inf)
  611.  
  612.     def h(self, node):
  613.         """h function is straight-line distance from a node's state to goal."""
  614.         locs = getattr(self.graph, 'locations', None)
  615.         if locs:
  616.             return int(distance(locs[node.state], locs[self.goal]))
  617.         else:
  618.             return math.inf
  619.  
  620.  
  621.  
  622. Pocetok = input()
  623. Stanica1 = input()
  624. Stanica2 = input()
  625. Kraj = input()
  626.  
  627. locations = dict(
  628. A = (2,1) , B = (2,4) , C = (2,10) ,
  629. D = (2,15) , E = (2,19) , F = (5,9) ,
  630. G = (4,11) , H = (8,1) , I = (8,5),
  631. J = (8,8) , K = (8,13) , L = (8,15),
  632. M = (8,19))
  633.  
  634. ABdistance = distance(locations['A'], locations['B'])
  635. BIdistance = distance(locations['B'], locations['I'])
  636. BCdistance = distance(locations['C'], locations['C'])
  637. HIdistance = distance(locations['H'], locations['I'])
  638. IJdistance = distance(locations['I'], locations['J'])
  639. FCdistance = distance(locations['F'], locations['C'])
  640. GCdistance = distance(locations['G'], locations['C'])
  641. CDdistance = distance(locations['C'], locations['D'])
  642. FGdistance = distance(locations['F'], locations['G'])
  643. FJdistance = distance(locations['F'], locations['J'])
  644. KGdistance = distance(locations['K'], locations['G'])
  645. LKdistance = distance(locations['L'], locations['K'])
  646. DEdistance = distance(locations['D'], locations['E'])
  647. DLdistance = distance(locations['D'], locations['L'])
  648. LMdistance = distance(locations['L'], locations['M'])
  649.  
  650.  
  651.  
  652. graph = UndirectedGraph({
  653.     "B": {"A": ABdistance, "I": BIdistance, "C": BCdistance},
  654.     "I": {"H": HIdistance, "J": IJdistance},
  655.     "C": {"F": FCdistance, "G": GCdistance, "D": CDdistance},
  656.     "F": {"G": FGdistance, "J": FJdistance},
  657.     "K": {"G": KGdistance, "L": LKdistance},
  658.     "D": {"E": DEdistance, "L": DLdistance},
  659.     "M": {"L": LMdistance}
  660. })
  661.  
  662.  
  663.  
  664. graph.locations = locations
  665.  
  666. problem_stanica1 = GraphProblem(Pocetok,Stanica1,graph)
  667. problem_stanica1_final = GraphProblem(Stanica1,Kraj,graph)
  668.  
  669. stanica1_r1 = astar_search(problem_stanica1).solve()
  670. stanica1_r2 = astar_search(problem_stanica1_final).solve()
  671. result_stanica1 = stanica1_r1 + stanica1_r2[1:]
  672.  
  673.  
  674. problem_stanica2 = GraphProblem(Pocetok,Stanica2,graph)
  675. problem_stanica2_final = GraphProblem(Stanica2,Kraj,graph)
  676.  
  677. stanica2_r1 = astar_search(problem_stanica2).solve()
  678. stanica2_r2 = astar_search(problem_stanica2_final).solve()
  679. result_stanica2 = stanica2_r1 + stanica2_r2[1:]
  680.  
  681. #CHECK-STATUS: FALSE
  682. if result_stanica1.__len__() == result_stanica2.__len__():
  683.     print(result_stanica1 , "\nStanica1")
  684. elif result_stanica1.__len__() < result_stanica2.__len__():
  685.     print(result_stanica1,"\nStanica1")
  686. else:
  687.     print(result_stanica2, "\nStanica2")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement