Advertisement
Guest User

Untitled

a guest
Jun 15th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 30.44 KB | None | 0 0
  1. # coding=utf-8
  2. import sys
  3. import math
  4. import random
  5. import bisect
  6. from sys import maxsize as infinity
  7.  
  8. """
  9. Дефинирање на класа за структурата на проблемот кој ќе го решаваме со пребарување.
  10. Класата Problem е апстрактна класа од која правиме наследување за дефинирање на основните
  11. карактеристики на секој проблем што сакаме да го решиме
  12. """
  13.  
  14.  
  15. class Problem:
  16.     def __init__(self, initial, goal=None):
  17.         self.initial = initial
  18.         self.goal = goal
  19.  
  20.     def successor(self, state):
  21.         """За дадена состојба, врати речник од парови {акција : состојба}
  22.        достапни од оваа состојба. Ако има многу следбеници, употребете
  23.        итератор кој би ги генерирал следбениците еден по еден, наместо да
  24.        ги генерирате сите одеднаш.
  25.  
  26.        :param state: дадена состојба
  27.        :return:  речник од парови {акција : состојба} достапни од оваа
  28.                  состојба
  29.        :rtype: dict
  30.        """
  31.         raise NotImplementedError
  32.  
  33.     def actions(self, state):
  34.         """За дадена состојба state, врати листа од сите акции што може да
  35.        се применат над таа состојба
  36.  
  37.        :param state: дадена состојба
  38.        :return: листа на акции
  39.        :rtype: list
  40.        """
  41.         raise NotImplementedError
  42.  
  43.     def result(self, state, action):
  44.         """За дадена состојба state и акција action, врати ја состојбата
  45.        што се добива со примена на акцијата над состојбата
  46.  
  47.        :param state: дадена состојба
  48.        :param action: дадена акција
  49.        :return: резултантна состојба
  50.        """
  51.         raise NotImplementedError
  52.  
  53.     def goal_test(self, state):
  54.         """Врати True ако state е целна состојба. Даденава имплементација
  55.        на методот директно ја споредува state со self.goal, како што е
  56.        специфицирана во конструкторот. Имплементирајте го овој метод ако
  57.        проверката со една целна состојба self.goal не е доволна.
  58.  
  59.        :param state: дадена состојба
  60.        :return: дали дадената состојба е целна состојба
  61.        :rtype: bool
  62.        """
  63.         return state == self.goal
  64.  
  65.     def path_cost(self, c, state1, action, state2):
  66.         """Врати ја цената на решавачкиот пат кој пристигнува во состојбата
  67.        state2 од состојбата state1 преку акцијата action, претпоставувајќи
  68.        дека цената на патот до состојбата state1 е c. Ако проблемот е таков
  69.        што патот не е важен, оваа функција ќе ја разгледува само состојбата
  70.        state2. Ако патот е важен, ќе ја разгледува цената c и можеби и
  71.        state1 и action. Даденава имплементација му доделува цена 1 на секој
  72.        чекор од патот.
  73.  
  74.        :param c: цена на патот до состојбата state1
  75.        :param state1: дадена моментална состојба
  76.        :param action: акција која треба да се изврши
  77.        :param state2: состојба во која треба да се стигне
  78.        :return: цена на патот по извршување на акцијата
  79.        :rtype: float
  80.        """
  81.         return c + 1
  82.  
  83.     def value(self):
  84.         """За проблеми на оптимизација, секоја состојба си има вредност.
  85.        Hill-climbing и сличните алгоритми се обидуваат да ја максимизираат
  86.        оваа вредност.
  87.  
  88.        :return: вредност на состојба
  89.        :rtype: float
  90.        """
  91.         raise NotImplementedError
  92.  
  93.  
  94.  
  95. def get_stars(my_stars,new_human_pos):
  96.     new_stars = list()
  97.     for i in range(2):
  98.         if my_stars[i]==new_human_pos:
  99.             new_stars.append(-1)
  100.         else:
  101.             new_stars.append(my_stars[i])
  102.  
  103.    # print(new_stars)
  104.     return tuple(new_stars)
  105.  
  106. def get_edges(edges,human_pos,new_human_pos):
  107.     new_edges=list()
  108.     for edge in edges:
  109.         if edge!=(human_pos,new_human_pos) and edge!=(new_human_pos,human_pos):
  110.             new_edges.append(tuple(edge))
  111.  
  112.     return tuple(new_edges)
  113.  
  114. class Explorer(Problem):
  115.  
  116.     def successor(self, state):
  117.         dictionary=dict()
  118.         human_pos=state[0]
  119.         edges=state[1]
  120.         my_stars=state[2]
  121.         # Desno
  122.         if (human_pos, human_pos + 1) in edges or (human_pos + 1, human_pos) in edges:
  123.             new_human_pos = human_pos + 1
  124.             new_stars = get_stars(my_stars, new_human_pos)
  125.             new_edges = get_edges(edges, human_pos, new_human_pos)
  126.             dictionary["Desno"] = new_human_pos, new_edges, new_stars
  127.         if (human_pos, human_pos - 1) in edges or (human_pos - 1, human_pos) in edges:
  128.             new_human_pos = human_pos - 1
  129.             new_stars = get_stars(my_stars, new_human_pos)
  130.             new_edges = get_edges(edges, human_pos, new_human_pos)
  131.             dictionary["Levo"] = new_human_pos, new_edges, new_stars
  132.         # Dolu
  133.         if (human_pos, human_pos + 4) in edges or (human_pos + 4, human_pos) in edges:
  134.             new_human_pos = human_pos + 4
  135.             new_stars = get_stars(my_stars, new_human_pos)
  136.             new_edges = get_edges(edges, human_pos, new_human_pos)
  137.             dictionary["Dolu"] = new_human_pos, new_edges, new_stars
  138.  
  139.         #Gore
  140.         if ((human_pos,human_pos-4) in edges) or ((human_pos-4,human_pos) in edges):
  141.             new_human_pos=human_pos-4
  142.             new_stars=get_stars(my_stars,new_human_pos)
  143.             new_edges=get_edges(edges,human_pos,new_human_pos)
  144.             dictionary["Gore"]=new_human_pos,new_edges,new_stars
  145.  
  146.  
  147.  
  148.         #DoluDesno
  149.         if (human_pos,human_pos+5) in edges or (human_pos+5,human_pos) in edges:
  150.             new_human_pos=human_pos+5
  151.             new_stars=get_stars(my_stars,new_human_pos)
  152.             new_edges=get_edges(edges,human_pos,new_human_pos)
  153.             dictionary["DoluDesno"]=new_human_pos,new_edges,new_stars
  154.         #GoreLevo
  155.         if (human_pos,human_pos-5) in edges or (human_pos-5,human_pos) in edges:
  156.             new_human_pos=human_pos-5
  157.             new_stars=get_stars(my_stars,new_human_pos)
  158.             new_edges=get_edges(edges,human_pos,new_human_pos)
  159.             dictionary["GoreLevo"]=new_human_pos,new_edges,new_stars
  160.  
  161.         return dictionary
  162.  
  163.     def actions(self, state):
  164.         return self.successor(state)
  165.  
  166.     def result(self, state, action):
  167.         return self.successor(state)[action]
  168.  
  169.     def value(self):
  170.         pass
  171.  
  172.     def goal_test(self, state):
  173.         my_stars=state[2]
  174.         return my_stars[0]==-1 and my_stars[1]==-1
  175.  
  176.  
  177. """
  178. Дефинирање на класата за структурата на јазел од пребарување.
  179. Класата Node не се наследува
  180. """
  181.  
  182.  
  183. class Node:
  184.     def __init__(self, state, parent=None, action=None, path_cost=0):
  185.         """Креирај јазол од пребарувачкото дрво, добиен од parent со примена
  186.        на акцијата action
  187.  
  188.        :param state: моментална состојба (current state)
  189.        :param parent: родителска состојба (parent state)
  190.        :param action: акција (action)
  191.        :param path_cost: цена на патот (path cost)
  192.        """
  193.         self.state = state
  194.         self.parent = parent
  195.         self.action = action
  196.         self.path_cost = path_cost
  197.         self.depth = 0  # search depth
  198.         if parent:
  199.             self.depth = parent.depth + 1
  200.  
  201.     def __repr__(self):
  202.         return "<Node %s>" % (self.state,)
  203.  
  204.     def __lt__(self, node):
  205.         return self.state < node.state
  206.  
  207.     def expand(self, problem):
  208.         """Излистај ги јазлите достапни во еден чекор од овој јазол.
  209.  
  210.        :param problem: даден проблем
  211.        :return: листа на достапни јазли во еден чекор
  212.        :rtype: list(Node)
  213.        """
  214.  
  215.         return [self.child_node(problem, action)
  216.                 for action in problem.actions(self.state)]
  217.  
  218.     def child_node(self, problem, action):
  219.         """Дете јазел
  220.  
  221.        :param problem: даден проблем
  222.        :param action: дадена акција
  223.        :return: достапен јазел според дадената акција
  224.        :rtype: Node
  225.        """
  226.         next_state = problem.result(self.state, action)
  227.         return Node(next_state, self, action,
  228.                     problem.path_cost(self.path_cost, self.state,
  229.                                       action, next_state))
  230.  
  231.     def solution(self):
  232.         """Врати ја секвенцата од акции за да се стигне од коренот до овој јазол.
  233.  
  234.        :return: секвенцата од акции
  235.        :rtype: list
  236.        """
  237.         return [node.action for node in self.path()[1:]]
  238.  
  239.     def solve(self):
  240.         """Врати ја секвенцата од состојби за да се стигне од коренот до овој јазол.
  241.  
  242.        :return: листа од состојби
  243.        :rtype: list
  244.        """
  245.         return [node.state for node in self.path()[0:]]
  246.  
  247.     def path(self):
  248.         """Врати ја листата од јазли што го формираат патот од коренот до овој јазол.
  249.  
  250.        :return: листа од јазли од патот
  251.        :rtype: list(Node)
  252.        """
  253.         x, result = self, []
  254.         while x:
  255.             result.append(x)
  256.             x = x.parent
  257.         result.reverse()
  258.         return result
  259.  
  260.     """Сакаме редицата од јазли кај breadth_first_search или
  261.    astar_search да не содржи состојби - дупликати, па јазлите што
  262.    содржат иста состојба ги третираме како исти. [Проблем: ова може
  263.    да не биде пожелно во други ситуации.]"""
  264.  
  265.     def __eq__(self, other):
  266.         return isinstance(other, Node) and self.state == other.state
  267.  
  268.     def __hash__(self):
  269.         return hash(self.state)
  270.  
  271.  
  272. """
  273. Дефинирање на помошни структури за чување на листата на генерирани, но непроверени јазли
  274. """
  275.  
  276.  
  277. class Queue:
  278.     """Queue е апстрактна класа / интерфејс. Постојат 3 типа:
  279.        Stack(): Last In First Out Queue (стек).
  280.        FIFOQueue(): First In First Out Queue (редица).
  281.        PriorityQueue(order, f): Queue во сортиран редослед (подразбирливо,од најмалиот кон
  282.                                 најголемиот јазол).
  283.    """
  284.  
  285.     def __init__(self):
  286.         raise NotImplementedError
  287.  
  288.     def append(self, item):
  289.         """Додади го елементот item во редицата
  290.  
  291.        :param item: даден елемент
  292.        :return: None
  293.        """
  294.         raise NotImplementedError
  295.  
  296.     def extend(self, items):
  297.         """Додади ги елементите items во редицата
  298.  
  299.        :param items: дадени елементи
  300.        :return: None
  301.        """
  302.         raise NotImplementedError
  303.  
  304.     def pop(self):
  305.         """Врати го првиот елемент од редицата
  306.  
  307.        :return: прв елемент
  308.        """
  309.         raise NotImplementedError
  310.  
  311.     def __len__(self):
  312.         """Врати го бројот на елементи во редицата
  313.  
  314.        :return: број на елементи во редицата
  315.        :rtype: int
  316.        """
  317.         raise NotImplementedError
  318.  
  319.     def __contains__(self, item):
  320.         """Проверка дали редицата го содржи елементот item
  321.  
  322.        :param item: даден елемент
  323.        :return: дали queue го содржи item
  324.        :rtype: bool
  325.        """
  326.         raise NotImplementedError
  327.  
  328.  
  329. class Stack(Queue):
  330.     """Last-In-First-Out Queue."""
  331.  
  332.     def __init__(self):
  333.         self.data = []
  334.  
  335.     def append(self, item):
  336.         self.data.append(item)
  337.  
  338.     def extend(self, items):
  339.         self.data.extend(items)
  340.  
  341.     def pop(self):
  342.         return self.data.pop()
  343.  
  344.     def __len__(self):
  345.         return len(self.data)
  346.  
  347.     def __contains__(self, item):
  348.         return item in self.data
  349.  
  350.  
  351. class FIFOQueue(Queue):
  352.     """First-In-First-Out Queue."""
  353.  
  354.     def __init__(self):
  355.         self.data = []
  356.  
  357.     def append(self, item):
  358.         self.data.append(item)
  359.  
  360.     def extend(self, items):
  361.         self.data.extend(items)
  362.  
  363.     def pop(self):
  364.         return self.data.pop(0)
  365.  
  366.     def __len__(self):
  367.         return len(self.data)
  368.  
  369.     def __contains__(self, item):
  370.         return item in self.data
  371.  
  372.  
  373. class PriorityQueue(Queue):
  374.     """Редица во која прво се враќа минималниот (или максималниот) елемент
  375.    (како што е определено со f и order). Оваа структура се користи кај
  376.    информирано пребарување"""
  377.     """"""
  378.  
  379.     def __init__(self, order=min, f=lambda x: x):
  380.         """
  381.        :param order: функција за подредување, ако order е min, се враќа елементот
  382.                      со минимална f(x); ако order е max, тогаш се враќа елементот
  383.                      со максимална f(x).
  384.        :param f: функција f(x)
  385.        """
  386.         assert order in [min, max]
  387.         self.data = []
  388.         self.order = order
  389.         self.f = f
  390.  
  391.     def append(self, item):
  392.         bisect.insort_right(self.data, (self.f(item), item))
  393.  
  394.     def extend(self, items):
  395.         for item in items:
  396.             bisect.insort_right(self.data, (self.f(item), item))
  397.  
  398.     def pop(self):
  399.         if self.order == min:
  400.             return self.data.pop(0)[1]
  401.         return self.data.pop()[1]
  402.  
  403.     def __len__(self):
  404.         return len(self.data)
  405.  
  406.     def __contains__(self, item):
  407.         return any(item == pair[1] for pair in self.data)
  408.  
  409.     def __getitem__(self, key):
  410.         for _, item in self.data:
  411.             if item == key:
  412.                 return item
  413.  
  414.     def __delitem__(self, key):
  415.         for i, (value, item) in enumerate(self.data):
  416.             if item == key:
  417.                 self.data.pop(i)
  418.  
  419.  
  420. """
  421. Неинформирано пребарување во рамки на дрво.
  422. Во рамки на дрвото не разрешуваме јамки.
  423. """
  424.  
  425.  
  426. def tree_search(problem, fringe):
  427.     """ Пребарувај низ следбениците на даден проблем за да најдеш цел.
  428.  
  429.    :param problem: даден проблем
  430.    :param fringe:  празна редица (queue)
  431.    :return: Node
  432.    """
  433.     fringe.append(Node(problem.initial))
  434.     while fringe:
  435.         node = fringe.pop()
  436.         print(node.state)
  437.         if problem.goal_test(node.state):
  438.             return node
  439.         fringe.extend(node.expand(problem))
  440.     return None
  441.  
  442.  
  443. def breadth_first_tree_search(problem):
  444.     """Експандирај го прво најплиткиот јазол во пребарувачкото дрво.
  445.  
  446.    :param problem: даден проблем
  447.    :return: Node
  448.    """
  449.     return tree_search(problem, FIFOQueue())
  450.  
  451.  
  452. def depth_first_tree_search(problem):
  453.     """Експандирај го прво најдлабокиот јазол во пребарувачкото дрво.
  454.  
  455.    :param problem:даден проблем
  456.    :return: Node
  457.    """
  458.     return tree_search(problem, Stack())
  459.  
  460.  
  461. """
  462. Неинформирано пребарување во рамки на граф
  463. Основната разлика е во тоа што овде не дозволуваме јамки,
  464. т.е. повторување на состојби
  465. """
  466.  
  467.  
  468. def graph_search(problem, fringe):
  469.     """Пребарувај низ следбениците на даден проблем за да најдеш цел.
  470.     Ако до дадена состојба стигнат два пата, употреби го најдобриот пат.
  471.  
  472.    :param problem: даден проблем
  473.    :param fringe: празна редица (queue)
  474.    :return: Node
  475.    """
  476.     closed = set()
  477.     fringe.append(Node(problem.initial))
  478.     while fringe:
  479.         node = fringe.pop()
  480.         if problem.goal_test(node.state):
  481.             return node
  482.         if node.state not in closed:
  483.             closed.add(node.state)
  484.             fringe.extend(node.expand(problem))
  485.     return None
  486.  
  487.  
  488. def breadth_first_graph_search(problem):
  489.     """Експандирај го прво најплиткиот јазол во пребарувачкиот граф.
  490.  
  491.    :param problem: даден проблем
  492.    :return: Node
  493.    """
  494.     return graph_search(problem, FIFOQueue())
  495.  
  496.  
  497. def depth_first_graph_search(problem):
  498.     """Експандирај го прво најдлабокиот јазол во пребарувачкиот граф.
  499.  
  500.    :param problem: даден проблем
  501.    :return: Node
  502.    """
  503.     return graph_search(problem, Stack())
  504.  
  505.  
  506. def depth_limited_search(problem, limit=50):
  507.     def recursive_dls(node, problem, limit):
  508.         """Помошна функција за depth limited"""
  509.         cutoff_occurred = False
  510.         if problem.goal_test(node.state):
  511.             return node
  512.         elif node.depth == limit:
  513.             return 'cutoff'
  514.         else:
  515.             for successor in node.expand(problem):
  516.                 result = recursive_dls(successor, problem, limit)
  517.                 if result == 'cutoff':
  518.                     cutoff_occurred = True
  519.                 elif result is not None:
  520.                     return result
  521.         if cutoff_occurred:
  522.             return 'cutoff'
  523.         return None
  524.  
  525.     return recursive_dls(Node(problem.initial), problem, limit)
  526.  
  527.  
  528. def iterative_deepening_search(problem):
  529.     for depth in range(sys.maxsize):
  530.         result = depth_limited_search(problem, depth)
  531.         if result is not 'cutoff':
  532.             return result
  533.  
  534.  
  535. def uniform_cost_search(problem):
  536.     """Експандирај го прво јазолот со најниска цена во пребарувачкиот граф."""
  537.     return graph_search(problem, PriorityQueue(min, lambda a: a.path_cost))
  538.  
  539.  
  540. """
  541. Информирано пребарување во рамки на граф
  542. """
  543.  
  544.  
  545. def memoize(fn, slot=None):
  546.     """ Запамети ја пресметаната вредност за која била листа од
  547.    аргументи. Ако е специфициран slot, зачувај го резултатот во
  548.    тој slot на првиот аргумент. Ако slot е None, зачувај ги
  549.    резултатите во речник.
  550.  
  551.    :param fn: зададена функција
  552.    :param slot: име на атрибут во кој се чуваат резултатите од функцијата
  553.    :return: функција со модификација за зачувување на резултатите
  554.    """
  555.     if slot:
  556.         def memoized_fn(obj, *args):
  557.             if hasattr(obj, slot):
  558.                 return getattr(obj, slot)
  559.             else:
  560.                 val = fn(obj, *args)
  561.                 setattr(obj, slot, val)
  562.                 return val
  563.     else:
  564.         def memoized_fn(*args):
  565.             if args not in memoized_fn.cache:
  566.                 memoized_fn.cache[args] = fn(*args)
  567.             return memoized_fn.cache[args]
  568.  
  569.         memoized_fn.cache = {}
  570.     return memoized_fn
  571.  
  572.  
  573. def best_first_graph_search(problem, f):
  574.     """Пребарувај низ следбениците на даден проблем за да најдеш цел. Користи
  575.     функција за евалуација за да се одлучи кој е сосед најмногу ветува и
  576.     потоа да се истражи. Ако до дадена состојба стигнат два пата, употреби
  577.     го најдобриот пат.
  578.  
  579.    :param problem: даден проблем
  580.    :param f: дадена функција за евристика
  581.    :return: Node or None
  582.    """
  583.     f = memoize(f, 'f')
  584.     node = Node(problem.initial)
  585.     if problem.goal_test(node.state):
  586.         return node
  587.     frontier = PriorityQueue(min, f)
  588.     frontier.append(node)
  589.     explored = set()
  590.     while frontier:
  591.         node = frontier.pop()
  592.         if problem.goal_test(node.state):
  593.             return node
  594.         explored.add(node.state)
  595.         for child in node.expand(problem):
  596.             if child.state not in explored and child not in frontier:
  597.                 frontier.append(child)
  598.             elif child in frontier:
  599.                 incumbent = frontier[child]
  600.                 if f(child) < f(incumbent):
  601.                     del frontier[incumbent]
  602.                     frontier.append(child)
  603.     return None
  604.  
  605.  
  606. def greedy_best_first_graph_search(problem, h=None):
  607.     """ Greedy best-first пребарување се остварува ако се специфицира дека f(n) = h(n).
  608.  
  609.    :param problem: даден проблем
  610.    :param h: дадена функција за евристика
  611.    :return: Node or None
  612.    """
  613.     h = memoize(h or problem.h, 'h')
  614.     return best_first_graph_search(problem, h)
  615.  
  616.  
  617. def astar_search(problem, h=None):
  618.     """ A* пребарување е best-first graph пребарување каде f(n) = g(n) + h(n).
  619.  
  620.    :param problem: даден проблем
  621.    :param h: дадена функција за евристика
  622.    :return: Node or None
  623.    """
  624.     h = memoize(h or problem.h, 'h')
  625.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  626.  
  627.  
  628. def recursive_best_first_search(problem, h=None):
  629.     """Recursive best first search - ја ограничува рекурзијата
  630.    преку следење на f-вредноста на најдобриот алтернативен пат
  631.    од било кој јазел предок (еден чекор гледање нанапред).
  632.  
  633.    :param problem: даден проблем
  634.    :param h: дадена функција за евристика
  635.    :return: Node or None
  636.    """
  637.     h = memoize(h or problem.h, 'h')
  638.  
  639.     def RBFS(problem, node, flimit):
  640.         if problem.goal_test(node.state):
  641.             return node, 0  # (втората вредност е неважна)
  642.         successors = node.expand(problem)
  643.         if len(successors) == 0:
  644.             return None, infinity
  645.         for s in successors:
  646.             s.f = max(s.path_cost + h(s), node.f)
  647.         while True:
  648.             # Подреди ги според најниската f вредност
  649.             successors.sort(key=lambda x: x.f)
  650.             best = successors[0]
  651.             if best.f > flimit:
  652.                 return None, best.f
  653.             if len(successors) > 1:
  654.                 alternative = successors[1].f
  655.             else:
  656.                 alternative = infinity
  657.             result, best.f = RBFS(problem, best, min(flimit, alternative))
  658.             if result is not None:
  659.                 return result, best.f
  660.  
  661.     node = Node(problem.initial)
  662.     node.f = h(node)
  663.     result, bestf = RBFS(problem, node, infinity)
  664.     return result
  665.  
  666.  
  667. """
  668. Пребарување низ проблем дефиниран како конечен граф
  669. """
  670.  
  671.  
  672. def distance(a, b):
  673.     """Растојание помеѓу две (x, y) точки."""
  674.     return math.hypot((a[0] - b[0]), (a[1] - b[1]))
  675.  
  676.  
  677. class Graph:
  678.     def __init__(self, dictionary=None, directed=True):
  679.         self.dict = dictionary or {}
  680.         self.directed = directed
  681.         if not directed:
  682.             self.make_undirected()
  683.         else:
  684.             # додади празен речник за линковите на оние јазли кои немаат
  685.             # насочени врски и не се дадени како клучеви во речникот
  686.             nodes_no_edges = list({y for x in self.dict.values()
  687.                                    for y in x if y not in self.dict})
  688.             for node in nodes_no_edges:
  689.                 self.dict[node] = {}
  690.  
  691.     def make_undirected(self):
  692.         """Ориентираниот граф претвори го во неориентиран со додавање
  693.        на симетричните ребра."""
  694.         for a in list(self.dict.keys()):
  695.             for (b, dist) in self.dict[a].items():
  696.                 self.connect1(b, a, dist)
  697.  
  698.     def connect(self, node_a, node_b, distance_val=1):
  699.         """Додади ребро од A до B со дадено растојание, а додади го и
  700.        обратното ребро (од B до A) ако графот е неориентиран."""
  701.         self.connect1(node_a, node_b, distance_val)
  702.         if not self.directed:
  703.             self.connect1(node_b, node_a, distance_val)
  704.  
  705.     def connect1(self, node_a, node_b, distance_val):
  706.         """Додади ребро од A до B со дадено растојание, но само во
  707.        едната насока."""
  708.         self.dict.setdefault(node_a, {})[node_b] = distance_val
  709.  
  710.     def get(self, a, b=None):
  711.         """Врати растојание придружено на ребро или пак врати речник
  712.        чии елементи се од обликот {јазол : растојание}.
  713.        .get(a,b) го враќа растојанието или пак враќа None
  714.        .get(a) враќа речник со елементи од обликот {јазол : растојание},
  715.            кој може да биде и празен – {}."""
  716.         links = self.dict.get(a)
  717.         if b is None:
  718.             return links
  719.         else:
  720.             return links.get(b)
  721.  
  722.     def nodes(self):
  723.         """Врати листа од јазлите во графот."""
  724.         return list(self.dict.keys())
  725.  
  726.  
  727. def UndirectedGraph(dictionary=None):
  728.     """Изгради Graph во кој што секое ребро (вклучувајќи ги и идните
  729.    ребра) е двонасочно."""
  730.     return Graph(dictionary=dictionary, directed=False)
  731.  
  732.  
  733. def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
  734.                 curvature=lambda: random.uniform(1.1, 1.5)):
  735.     """Construct a random graph, with the specified nodes, and random links.
  736.    The nodes are laid out randomly on a (width x height) rectangle.
  737.    Then each node is connected to the min_links nearest neighbors.
  738.    Because inverse links are added, some nodes will have more connections.
  739.    The distance between nodes is the hypotenuse times curvature(),
  740.    where curvature() defaults to a random number between 1.1 and 1.5."""
  741.     g = UndirectedGraph()
  742.     g.locations = {}
  743.     # Build the cities
  744.     for node in nodes:
  745.         g.locations[node] = (random.randrange(width), random.randrange(height))
  746.     # Build roads from each city to at least min_links nearest neighbors.
  747.     for i in range(min_links):
  748.         for node in nodes:
  749.             if len(g.get(node)) < min_links:
  750.                 here = g.locations[node]
  751.  
  752.                 def distance_to_node(n):
  753.                     if n is node or g.get(node, n):
  754.                         return math.inf
  755.                     return distance(g.locations[n], here)
  756.  
  757.                 neighbor = nodes.index(min(nodes, key=distance_to_node))
  758.                 d = distance(g.locations[neighbor], here) * curvature()
  759.                 g.connect(node, neighbor, int(d))
  760.     return g
  761.  
  762.  
  763. class GraphProblem(Problem):
  764.     """Проблем на пребарување на граф од еден до друг јазол."""
  765.  
  766.     def __init__(self, initial, goal, graph):
  767.         super().__init__(initial, goal)
  768.         self.graph = graph
  769.  
  770.     def actions(self, state):
  771.         """Акциите кај јазол во граф се едноставно - неговите соседи."""
  772.         return list(self.graph.get(state).keys())
  773.  
  774.     def result(self, state, action):
  775.         """Резултат на одењето кон сосед е самиот тој сосед."""
  776.         return action
  777.  
  778.     def path_cost(self, c, state1, action, state2):
  779.         return c + (self.graph.get(state1, state2) or math.inf)
  780.  
  781.     def h(self, node):
  782.         """Функцијата h е праволиниско растојание од состојбата зачувана
  783.        во тековниот јазол до целната состојба."""
  784.         locs = getattr(self.graph, 'locations', None)
  785.         if locs:
  786.             return int(distance(locs[node.state], locs[self.goal]))
  787.         else:
  788.             return math.inf
  789.  
  790.  
  791.  
  792. IgracPozicija = int(input())
  793. Z1Pozicija = int(input())
  794. Z2Pozicija = int(input())
  795.  
  796. current_edges=(
  797.     (1,2),(3,4),(1,5),(2,6),(3,7),(4,8),
  798.     (5,6),(6,7),(7,8),(6,10),(6,11),(7,11),
  799.     (9,10),(10,11),(11,12),(9,13),(10,14),(11,15),(12,16),
  800.     (13,14),(15,16)
  801. )
  802.  
  803. stars=Z1Pozicija,Z2Pozicija
  804. initial_state=IgracPozicija,current_edges,stars
  805. problem=Explorer(initial_state)
  806. solver=breadth_first_graph_search(problem)
  807. print(solver.solution())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement