Advertisement
Nikolovska

[ВИ] лаб 4.2 Патување низ Германија

Apr 23rd, 2018
576
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 30.50 KB | None | 0 0
  1. Pocetok = input()
  2. Kraj = input()
  3.  
  4.  
  5. import sys
  6. import bisect
  7.  
  8. infinity = float('inf')  # sistemski definirana vrednost za beskonecnost
  9.  
  10.  
  11. # ______________________________________________________________________________________________
  12. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  13.  
  14. class Queue:
  15.     """Queue is an abstract class/interface. There are three types:
  16.        Stack(): A Last In First Out Queue.
  17.        FIFOQueue(): A First In First Out Queue.
  18.        PriorityQueue(order, f): Queue in sorted order (default min-first).
  19.    Each type supports the following methods and functions:
  20.        q.append(item)  -- add an item to the queue
  21.        q.extend(items) -- equivalent to: for item in items: q.append(item)
  22.        q.pop()         -- return the top item from the queue
  23.        len(q)          -- number of items in q (also q.__len())
  24.        item in q       -- does q contain item?
  25.    Note that isinstance(Stack(), Queue) is false, because we implement stacks
  26.    as lists.  If Python ever gets interfaces, Queue will be an interface."""
  27.  
  28.     def __init__(self):
  29.         raise NotImplementedError
  30.  
  31.     def extend(self, items):
  32.         for item in items:
  33.             self.append(item)
  34.  
  35.  
  36. def Stack():
  37.     """A Last-In-First-Out Queue."""
  38.     return []
  39.  
  40.  
  41. class FIFOQueue(Queue):
  42.     """A First-In-First-Out Queue."""
  43.  
  44.     def __init__(self):
  45.         self.A = []
  46.         self.start = 0
  47.  
  48.     def append(self, item):
  49.         self.A.append(item)
  50.  
  51.     def __len__(self):
  52.         return len(self.A) - self.start
  53.  
  54.     def extend(self, items):
  55.         self.A.extend(items)
  56.  
  57.     def pop(self):
  58.         e = self.A[self.start]
  59.         self.start += 1
  60.         if self.start > 5 and self.start > len(self.A) / 2:
  61.             self.A = self.A[self.start:]
  62.             self.start = 0
  63.         return e
  64.  
  65.     def __contains__(self, item):
  66.         return item in self.A[self.start:]
  67.  
  68.  
  69. class PriorityQueue(Queue):
  70.     """A queue in which the minimum (or maximum) element (as determined by f and
  71.    order) is returned first. If order is min, the item with minimum f(x) is
  72.    returned first; if order is max, then it is the item with maximum f(x).
  73.    Also supports dict-like lookup. This structure will be most useful in informed searches"""
  74.  
  75.     def __init__(self, order=min, f=lambda x: x):
  76.         self.A = []
  77.         self.order = order
  78.         self.f = f
  79.  
  80.     def append(self, item):
  81.         bisect.insort(self.A, (self.f(item), item))
  82.  
  83.     def __len__(self):
  84.         return len(self.A)
  85.  
  86.     def pop(self):
  87.         if self.order == min:
  88.             return self.A.pop(0)[1]
  89.         else:
  90.             return self.A.pop()[1]
  91.  
  92.     def __contains__(self, item):
  93.         return any(item == pair[1] for pair in self.A)
  94.  
  95.     def __getitem__(self, key):
  96.         for _, item in self.A:
  97.             if item == key:
  98.                 return item
  99.  
  100.     def __delitem__(self, key):
  101.         for i, (value, item) in enumerate(self.A):
  102.             if item == key:
  103.                 self.A.pop(i)
  104.  
  105.  
  106. # ______________________________________________________________________________________________
  107. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  108. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  109. # na sekoj eden problem sto sakame da go resime
  110.  
  111.  
  112. class Problem:
  113.     """The abstract class for a formal problem.  You should subclass this and
  114.    implement the method successor, and possibly __init__, goal_test, and
  115.    path_cost. Then you will create instances of your subclass and solve them
  116.    with the various search functions."""
  117.  
  118.     def __init__(self, initial, goal=None):
  119.         """The constructor specifies the initial state, and possibly a goal
  120.        state, if there is a unique goal.  Your subclass's constructor can add
  121.        other arguments."""
  122.         self.initial = initial
  123.         self.goal = goal
  124.  
  125.     def successor(self, state):
  126.         """Given a state, return a dictionary of {action : state} pairs reachable
  127.        from this state. If there are many successors, consider an iterator
  128.        that yields the successors one at a time, rather than building them
  129.        all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  130.         raise NotImplementedError
  131.  
  132.     def actions(self, state):
  133.         """Given a state, return a list of all actions possible from that state"""
  134.         raise NotImplementedError
  135.  
  136.     def result(self, state, action):
  137.         """Given a state and action, return the resulting state"""
  138.         raise NotImplementedError
  139.  
  140.     def goal_test(self, state):
  141.         """Return True if the state is a goal. The default method compares the
  142.        state to self.goal, as specified in the constructor. Implement this
  143.        method if checking against a single self.goal is not enough."""
  144.         return state == self.goal
  145.  
  146.     def path_cost(self, c, state1, action, state2):
  147.         """Return the cost of a solution path that arrives at state2 from
  148.        state1 via action, assuming cost c to get up to state1. If the problem
  149.        is such that the path doesn't matter, this function will only look at
  150.        state2.  If the path does matter, it will consider c and maybe state1
  151.        and action. The default method costs 1 for every step in the path."""
  152.         return c + 1
  153.  
  154.     def value(self):
  155.         """For optimization problems, each state has a value.  Hill-climbing
  156.        and related algorithms try to maximize this value."""
  157.         raise NotImplementedError
  158.  
  159.  
  160. # ______________________________________________________________________________
  161. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  162. # Klasata Node ne se nasleduva
  163.  
  164. class Node:
  165.     """A node in a search tree. Contains a pointer to the parent (the node
  166.    that this is a successor of) and to the actual state for this node. Note
  167.    that if a state is arrived at by two paths, then there are two nodes with
  168.    the same state.  Also includes the action that got us to this state, and
  169.    the total path_cost (also known as g) to reach the node.  Other functions
  170.    may add an f and h value; see best_first_graph_search and astar_search for
  171.    an explanation of how the f and h values are handled. You will not need to
  172.    subclass this class."""
  173.  
  174.     def __init__(self, state, parent=None, action=None, path_cost=0):
  175.         "Create a search tree Node, derived from a parent by an action."
  176.         self.state = state
  177.         self.parent = parent
  178.         self.action = action
  179.         self.path_cost = path_cost
  180.         self.depth = 0
  181.         if parent:
  182.             self.depth = parent.depth + 1
  183.  
  184.     def __repr__(self):
  185.         return "<Node %s>" % (self.state,)
  186.  
  187.     def __lt__(self, node):
  188.         return self.state < node.state
  189.  
  190.     def expand(self, problem):
  191.         "List the nodes reachable in one step from this node."
  192.         return [self.child_node(problem, action)
  193.                 for action in problem.actions(self.state)]
  194.  
  195.     def child_node(self, problem, action):
  196.         "Return a child node from this node"
  197.         next = problem.result(self.state, action)
  198.         return Node(next, self, action,
  199.                     problem.path_cost(self.path_cost, self.state,
  200.                                       action, next))
  201.  
  202.     def solution(self):
  203.         "Return the sequence of actions to go from the root to this node."
  204.         return [node.action for node in self.path()[1:]]
  205.  
  206.     def solve(self):
  207.         "Return the sequence of states to go from the root to this node."
  208.         return [node.state for node in self.path()[0:]]
  209.  
  210.     def path(self):
  211.         "Return a list of nodes forming the path from the root to this node."
  212.         x, result = self, []
  213.         while x:
  214.             result.append(x)
  215.             x = x.parent
  216.         return list(reversed(result))
  217.  
  218.     # We want for a queue of nodes in breadth_first_search or
  219.     # astar_search to have no duplicated states, so we treat nodes
  220.     # with the same state as equal. [Problem: this may not be what you
  221.     # want in other contexts.]
  222.  
  223.     def __eq__(self, other):
  224.         return isinstance(other, Node) and self.state == other.state
  225.  
  226.     def __hash__(self):
  227.         return hash(self.state)
  228.  
  229.  
  230. # ________________________________________________________________________________________________________
  231. #Neinformirano prebaruvanje vo ramki na drvo
  232. #Vo ramki na drvoto ne razresuvame jamki
  233.  
  234. def tree_search(problem, fringe):
  235.     """Search through the successors of a problem to find a goal.
  236.    The argument fringe should be an empty queue."""
  237.     fringe.append(Node(problem.initial))
  238.     while fringe:
  239.         node = fringe.pop()
  240.         print node.state
  241.         if problem.goal_test(node.state):
  242.             return node
  243.         fringe.extend(node.expand(problem))
  244.     return None
  245.  
  246.  
  247. def breadth_first_tree_search(problem):
  248.     "Search the shallowest nodes in the search tree first."
  249.     return tree_search(problem, FIFOQueue())
  250.  
  251.  
  252. def depth_first_tree_search(problem):
  253.     "Search the deepest nodes in the search tree first."
  254.     return tree_search(problem, Stack())
  255.  
  256.  
  257. # ________________________________________________________________________________________________________
  258. #Neinformirano prebaruvanje vo ramki na graf
  259. #Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  260.  
  261. def graph_search(problem, fringe):
  262.     """Search through the successors of a problem to find a goal.
  263.    The argument fringe should be an empty queue.
  264.    If two paths reach a state, only use the best one."""
  265.     closed = {}
  266.     fringe.append(Node(problem.initial))
  267.     while fringe:
  268.         node = fringe.pop()
  269.         if problem.goal_test(node.state):
  270.             return node
  271.         if node.state not in closed:
  272.             closed[node.state] = True
  273.             fringe.extend(node.expand(problem))
  274.     return None
  275.  
  276.  
  277. def breadth_first_graph_search(problem):
  278.     "Search the shallowest nodes in the search tree first."
  279.     return graph_search(problem, FIFOQueue())
  280.  
  281.  
  282. def depth_first_graph_search(problem):
  283.     "Search the deepest nodes in the search tree first."
  284.     return graph_search(problem, Stack())
  285.  
  286.  
  287. def uniform_cost_search(problem):
  288.     "Search the nodes in the search tree with lowest cost first."
  289.     return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  290.  
  291.  
  292. def depth_limited_search(problem, limit=50):
  293.     "depth first search with limited depth"
  294.  
  295.     def recursive_dls(node, problem, limit):
  296.         "helper function for depth limited"
  297.         cutoff_occurred = False
  298.         if problem.goal_test(node.state):
  299.             return node
  300.         elif node.depth == limit:
  301.             return 'cutoff'
  302.         else:
  303.             for successor in node.expand(problem):
  304.                 result = recursive_dls(successor, problem, limit)
  305.                 if result == 'cutoff':
  306.                     cutoff_occurred = True
  307.                 elif result != None:
  308.                     return result
  309.         if cutoff_occurred:
  310.             return 'cutoff'
  311.         else:
  312.             return None
  313.  
  314.     # Body of depth_limited_search:
  315.     return recursive_dls(Node(problem.initial), problem, limit)
  316.  
  317.  
  318. def iterative_deepening_search(problem):
  319.  
  320.     for depth in xrange(sys.maxint):
  321.         result = depth_limited_search(problem, depth)
  322.         if result is not 'cutoff':
  323.             return result
  324.  
  325.  
  326. # ________________________________________________________________________________________________________
  327. #Pomosna funkcija za informirani prebaruvanja
  328. #So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  329.  
  330. def memoize(fn, slot=None):
  331.     """Memoize fn: make it remember the computed value for any argument list.
  332.    If slot is specified, store result in that slot of first argument.
  333.    If slot is false, store results in a dictionary."""
  334.     if slot:
  335.         def memoized_fn(obj, *args):
  336.             if hasattr(obj, slot):
  337.                 return getattr(obj, slot)
  338.             else:
  339.                 val = fn(obj, *args)
  340.                 setattr(obj, slot, val)
  341.                 return val
  342.     else:
  343.         def memoized_fn(*args):
  344.             if not memoized_fn.cache.has_key(args):
  345.                 memoized_fn.cache[args] = fn(*args)
  346.             return memoized_fn.cache[args]
  347.  
  348.         memoized_fn.cache = {}
  349.     return memoized_fn
  350.  
  351.  
  352. # ________________________________________________________________________________________________________
  353. #Informirano prebaruvanje vo ramki na graf
  354.  
  355. def best_first_graph_search(problem, f):
  356.     """Search the nodes with the lowest f scores first.
  357.    You specify the function f(node) that you want to minimize; for example,
  358.    if f is a heuristic estimate to the goal, then we have greedy best
  359.    first search; if f is node.depth then we have breadth-first search.
  360.    There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  361.    values will be cached on the nodes as they are computed. So after doing
  362.    a best first search you can examine the f values of the path returned."""
  363.  
  364.     f = memoize(f, 'f')
  365.     node = Node(problem.initial)
  366.     if problem.goal_test(node.state):
  367.         return node
  368.     frontier = PriorityQueue(min, f)
  369.     frontier.append(node)
  370.     explored = set()
  371.     while frontier:
  372.         node = frontier.pop()
  373.         if problem.goal_test(node.state):
  374.             return node
  375.         explored.add(node.state)
  376.         for child in node.expand(problem):
  377.             if child.state not in explored and child not in frontier:
  378.                 frontier.append(child)
  379.             elif child in frontier:
  380.                 incumbent = frontier[child]
  381.                 if f(child) < f(incumbent):
  382.                     del frontier[incumbent]
  383.                     frontier.append(child)
  384.     return None
  385.  
  386.  
  387. def greedy_best_first_graph_search(problem, h=None):
  388.     "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  389.     h = memoize(h or problem.h, 'h')
  390.     return best_first_graph_search(problem, h)
  391.  
  392.  
  393. def astar_search(problem, h=None):
  394.     "A* search is best-first graph search with f(n) = g(n)+h(n)."
  395.     h = memoize(h or problem.h, 'h')
  396.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  397.  
  398.  
  399. # ________________________________________________________________________________________________________
  400. #Dopolnitelni prebaruvanja
  401. #Recursive_best_first_search e implementiran
  402. #Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  403.  
  404. def recursive_best_first_search(problem, h=None):
  405.     h = memoize(h or problem.h, 'h')
  406.  
  407.     def RBFS(problem, node, flimit):
  408.         if problem.goal_test(node.state):
  409.             return node, 0  # (The second value is immaterial)
  410.         successors = node.expand(problem)
  411.         if len(successors) == 0:
  412.             return None, infinity
  413.         for s in successors:
  414.             s.f = max(s.path_cost + h(s), node.f)
  415.         while True:
  416.             # Order by lowest f value
  417.             successors.sort(key=lambda x: x.f)
  418.             best = successors[0]
  419.             if best.f > flimit:
  420.                 return None, best.f
  421.             if len(successors) > 1:
  422.                 alternative = successors[1].f
  423.             else:
  424.                 alternative = infinity
  425.             result, best.f = RBFS(problem, best, min(flimit, alternative))
  426.             if result is not None:
  427.                 return result, best.f
  428.  
  429.     node = Node(problem.initial)
  430.     node.f = h(node)
  431.     result, bestf = RBFS(problem, node, infinity)
  432.     return result
  433.  
  434.  
  435. # _________________________________________________________________________________________________________
  436. #PRIMER 1 : PROBLEM SO DVA SADA SO VODA
  437. #OPIS: Dadeni se dva sada J0 i J1 so kapaciteti C0 i C1
  438. #Na pocetok dvata sada se polni. Inicijalnata sostojba moze da se prosledi na pocetok
  439. #Problemot e kako da se stigne do sostojba vo koja J0 ke ima G0 litri, a J1 ke ima G1 litri
  440. #AKCII: 1. Da se isprazni bilo koj od sadovite
  441. #2. Da se prefrli tecnosta od eden sad vo drug so toa sto ne moze da se nadmine kapacitetot na sadovite
  442. # Moze da ima i opcionalen tret vid na akcii 3. Napolni bilo koj od sadovite (studentite da ja implementiraat ovaa varijanta)
  443. # ________________________________________________________________________________________________________
  444.  
  445. class WJ(Problem):
  446.     """STATE: Torka od oblik (3,2) if jug J0 has 3 liters and J1 2 liters
  447.    Opcionalno moze za nekoj od sadovite da se sretne i vrednost '*' sto znaci deka e nebitno kolku ima vo toj sad
  448.    GOAL: Predefinirana sostojba do kade sakame da stigneme. Ako ne interesira samo eden sad za drugiot mozeme da stavime '*'
  449.    PROBLEM: Se specificiraat kapacitetite na sadovite, pocetna sostojba i cel """
  450.  
  451.     def __init__(self, capacities=(5, 2), initial=(5, 0), goal=(0, 1)):
  452.         self.capacities = capacities
  453.         self.initial = initial
  454.         self.goal = goal
  455.  
  456.     def goal_test(self, state):
  457.         """ Vraka true ako sostojbata e celna """
  458.         g = self.goal
  459.         return (state[0] == g[0] or g[0] == '*') and \
  460.                (state[1] == g[1] or g[1] == '*')
  461.  
  462.     def successor(self, J):
  463.         """Vraka recnik od sledbenici na sostojbata"""
  464.         successors = dict()
  465.         J0, J1 = J
  466.         (C0, C1) = self.capacities
  467.         if J0 > 0:
  468.             Jnew = 0, J1
  469.             successors['dump jug 0'] = Jnew
  470.         if J1 > 0:
  471.             Jnew = J0, 0
  472.             successors['dump jug 1'] = Jnew
  473.         if J1 < C1 and J0 > 0:
  474.             delta = min(J0, C1 - J1)
  475.             Jnew = J0 - delta, J1 + delta
  476.             successors['pour jug 0 into jug 1'] = Jnew
  477.         if J0 < C0 and J1 > 0:
  478.             delta = min(J1, C0 - J0)
  479.             Jnew = J0 + delta, J1 - delta
  480.             successors['pour jug 1 into jug 0'] = Jnew
  481.         return successors
  482.  
  483.     def actions(self, state):
  484.         return self.successor(state).keys()
  485.  
  486.     def result(self, state, action):
  487.         possible = self.successor(state)
  488.         return possible[action]
  489.  
  490. # So vaka definiraniot problem mozeme da gi koristime site neinformirani prebaruvanja
  491. # Vo prodolzenie se dadeni mozni povici (vnimavajte za da moze da napravite povik mora da definirate problem)
  492. #
  493. #    WJInstance = WJ((5, 2), (5, 2), ('*', 1))
  494. #    print WJInstance
  495. #
  496. #    answer1 = breadth_first_tree_search(WJInstance)
  497. #    print answer1.solve()
  498. #
  499. #    answer2 = depth_first_tree_search(WJInstance) #vnimavajte na ovoj povik, moze da vleze vo beskonecna jamka
  500. #    print answer2.solve()
  501. #
  502. #    answer3 = breadth_first_graph_search(WJInstance)
  503. #    print answer3.solve()
  504. #
  505. #    answer4 = depth_first_graph_search(WJInstance)
  506. #    print answer4.solve()
  507. #
  508. #    answer5 = depth_limited_search(WJInstance)
  509. #    print answer5.solve()
  510. #
  511. #    answer6 = iterative_deepening_search(WJInstance)
  512. #    print answer6.solve()
  513.  
  514. # _________________________________________________________________________________________________________
  515. #PRIMER 2 : PROBLEM NA SLOZUVALKA
  516. #OPIS: Dadena e slozuvalka 3x3 na koja ima polinja so brojki od 1 do 8 i edno prazno pole
  517. # Praznoto pole e obelezano so *. Eden primer na slozuvalka e daden vo prodolzenie:
  518. #  -------------
  519. #  | * | 3 | 2 |
  520. #  |---|---|---|
  521. #  | 4 | 1 | 5 |
  522. #  |---|---|---|
  523. #  | 6 | 7 | 8 |
  524. #  -------------
  525. #Problemot e kako da se stigne do nekoja pocetna raspredelba na polinjata do nekoja posakuvana, na primer do:
  526. #  -------------
  527. #  | * | 1 | 2 |
  528. #  |---|---|---|
  529. #  | 3 | 4 | 5 |
  530. #  |---|---|---|
  531. #  | 6 | 7 | 8 |
  532. #  -------------
  533. #AKCII: Akciite ke gi gledame kako dvizenje na praznoto pole, pa mozni akcii se : gore, dole, levo i desno.
  534. #Pri definiranjeto na akciite mora da se vnimava dali akciite voopsto mozat da se prevzemat vo dadenata slozuvalka
  535. #STATE: Sostojbata ke ja definirame kako string koj ke ima 9 karakteri (po eden za sekoe brojce plus za *)
  536. #pri sto stringot ke se popolnuva so izminuvanje na slozuvalkata od prviot kon tretiot red, od levo kon desno.
  537. # Na primer sostojbata za pocetnata slozuvalka e: '*32415678'
  538. # Sostojbata za finalnata slozuvalka e: '*12345678'
  539. # ________________________________________________________________________________________________________
  540. #
  541.  
  542. default_goal = '*12345678' #predefinirana cel
  543.  
  544. #Ke definirame 3 klasi za problemot
  545. #Prvata klasa nema implementirano nikakva hevristika
  546.  
  547. class P8(Problem):
  548.  
  549.     name = 'No Heuristic'
  550.  
  551.     def __init__(self, goal=default_goal, initial=None, N=20):
  552.         self.goal = goal
  553.         self.initial = initial
  554.  
  555.     def successor(self, state):
  556.         return successor8(state)
  557.  
  558.     def actions(self, state):
  559.         return self.successor(state).keys()
  560.  
  561.     def h(self, node):
  562.         """Heuristic for 8 puzzle: returns 0"""
  563.         return 0
  564.  
  565.     def result(self, state, action):
  566.         possible = self.successor(state)
  567.         return possible[action]
  568.  
  569. #Slednite klasi ke nasleduvaat od prethodnata bez hevristika so toa sto ovde ke ja definirame i hevristikata
  570.  
  571. class P8_h1(P8):
  572.     """ Slozuvalka so hevristika
  573.    HEVRISTIKA: Brojot na polinja koi ne se na vistinskoto mesto"""
  574.  
  575.     name = 'Out of Place Heuristic'
  576.  
  577.     def h(self, node):
  578.         """Funkcija koja ja presmetuva hevristikata,
  579.        t.e. razlikata pomegu nekoj tekoven jazel od prebaruvanjeto i celniot jazel"""
  580.         matches = 0
  581.         for (t1, t2) in zip(node.state, self.goal):
  582.             #zip funkcijata od dve listi na vlez pravi edna lista od parovi (torki)
  583.             #primer: zip(['a','b','c'],[1,2,3]) == [('a',1),('b',2),('c',3)]
  584.             # zip('abc','123') == [('a','1'),('b','2'),('c','3')]
  585.             if t1 != t2:
  586.                 matches = + 1
  587.         return matches
  588.  
  589.  
  590. class P8_h2(P8):
  591.     """ Slozuvalka so hevristika
  592.    HEVRISTIKA: Menheten rastojanie do celna sostojba"""
  593.  
  594.     name = 'Manhattan Distance Heuristic (MHD)'
  595.  
  596.     def h(self, node):
  597.         """Funkcija koja ja presmetuva hevristikata,
  598.        t.e. Menheten rastojanieto pomegu nekoj tekoven jazel od prebaruvanjeto i celniot jazel, pri sto
  599.        Menheten rastojanieto megu jazlite e zbir od Menheten rastojanijata pomegu istite broevi vo dvata jazli"""
  600.         sum = 0
  601.         for c in '12345678':
  602.             sum = + mhd(node.state.index(c), self.goal.index(c)) #pomosna funkcija definirana vo prodolzenie
  603.         return sum
  604.  
  605.  
  606. # Za da mozeme da go definirame rastojanieto treba da definirame koordinaten sistem
  607. # Pozetokot na koordinatniot sistem e postaven vo gorniot lev agol na slozuvalkata
  608. # Definirame recnik za koordinatite na sekoe pole od slozuvalkata
  609. coordinates = {0: (0, 0), 1: (1, 0), 2: (2, 0),
  610.                3: (0, 1), 4: (1, 1), 5: (2, 1),
  611.                6: (0, 2), 7: (1, 2), 8: (2, 2)}
  612.  
  613. #Funkcija koja presmetuva Menheten rastojanie za slozuvalkata
  614. #Na vlez dobiva dva celi broja koi odgovaraat na dve polinja na koi se naogaat broevite za koi treba da presmetame rastojanie
  615. def mhd(n, m):
  616.     x1, y1 = coordinates[n]
  617.     x2, y2 = coordinates[m]
  618.     return abs(x1 - x2) + abs(y1 - y2)
  619.  
  620.  
  621.  
  622. def successor8(S):
  623.     """Pomosna funkcija koja generira recnik za sledbenicite na daden jazel"""
  624.  
  625.     blank = S.index('*') #kade se naoga praznoto pole
  626.  
  627.     succs = {}
  628.  
  629.     # GORE: Ako praznoto pole ne e vo prviot red, togas vo sostojbata napravi swap
  630.     # na praznoto pole so brojceto koe se naoga na poleto nad nego
  631.     if blank > 2:
  632.         swap = blank - 3
  633.         succs['GORE'] = S[0:swap] + '*' + S[swap + 1:blank] + S[swap] + S[blank + 1:]
  634.  
  635.     # DOLE: Ako praznoto pole ne e vo posledniot red, togas vo sostojbata napravi swap
  636.     # na praznoto pole so brojceto koe se naoga na poleto pod nego
  637.     if blank < 6:
  638.         swap = blank + 3
  639.         succs['DOLE'] = S[0:blank] + S[swap] + S[blank + 1:swap] + '*' + S[swap + 1:]
  640.  
  641.     # LEVO: Ako praznoto pole ne e vo prvata kolona, togas vo sostojbata napravi swap
  642.     # na praznoto pole so brojceto koe se naoga na poleto levo od nego
  643.     if blank % 3 > 0:
  644.         swap = blank - 1
  645.         succs['LEVO'] = S[0:swap] + '*' + S[swap] + S[blank + 1:]
  646.  
  647.     # DESNO: Ako praznoto pole ne e vo poslednata kolona, togas vo sostojbata napravi swap
  648.     # na praznoto pole so brojceto koe se naoga na poleto desno od nego
  649.     if blank % 3 < 2:
  650.         swap = blank + 1
  651.         succs['DESNO'] = S[0:blank] + S[swap] + '*' + S[swap + 1:]
  652.  
  653.     return succs
  654.  
  655. # So vaka definiraniot problem mozeme da gi koristime site informirani, no i neinformirani prebaruvanja
  656. # Vo prodolzenie se dadeni mozni povici (vnimavajte za da moze da napravite povik mora da definirate problem)
  657. #
  658. #    s='*32415678'
  659. #    p1=P8(initial=s)
  660. #    p2=P8_h1(initial=s)
  661. #    p3=P8_h2(initial=s)
  662. #
  663. #    answer1 = greedy_best_first_graph_search(p1)
  664. #    print answer1.solve()
  665. #
  666. #    answer2 = greedy_best_first_graph_search(p2)
  667. #    print answer2.solve()
  668. #
  669. #    answer3 = greedy_best_first_graph_search(p3)
  670. #    print answer3.solve()
  671. #
  672. #    answer4 = astar_search(p1)
  673. #    print answer4.solve()
  674. #
  675. #    answer5 = astar_search(p2)
  676. #    print answer5.solve()
  677. #
  678. #    answer6 = astar_search(p3)
  679. #    print answer6.solve()
  680. #
  681. #    answer7 = recursive_best_first_search(p1)
  682. #    print answer7.solve()
  683. #
  684. #    answer8 = recursive_best_first_search(p2)
  685. #    print answer8.solve()
  686. #
  687. #    answer9 = recursive_best_first_search(p3)
  688. #    print answer9.solve()
  689.  
  690. # Graphs and Graph Problems
  691.  
  692.  
  693. class Graph:
  694.  
  695.     """A graph connects nodes (verticies) by edges (links).  Each edge can also
  696.    have a length associated with it.  The constructor call is something like:
  697.        g = Graph({'A': {'B': 1, 'C': 2})
  698.    this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from
  699.    A to B,  and an edge of length 2 from A to C.  You can also do:
  700.        g = Graph({'A': {'B': 1, 'C': 2}, directed=False)
  701.    This makes an undirected graph, so inverse links are also added. The graph
  702.    stays undirected; if you add more links with g.connect('B', 'C', 3), then
  703.    inverse link is also added.  You can use g.nodes() to get a list of nodes,
  704.    g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the
  705.    length of the link from A to B.  'Lengths' can actually be any object at
  706.    all, and nodes can be any hashable object."""
  707.  
  708.     def __init__(self, dict=None, directed=True):
  709.         self.dict = dict or {}
  710.         self.directed = directed
  711.         if not directed:
  712.             self.make_undirected()
  713.  
  714.     def make_undirected(self):
  715.         """Make a digraph into an undirected graph by adding symmetric edges."""
  716.         for a in list(self.dict.keys()):
  717.             for (b, dist) in self.dict[a].items():
  718.                 self.connect1(b, a, dist)
  719.  
  720.     def connect(self, A, B, distance=1):
  721.         """Add a link from A and B of given distance, and also add the inverse
  722.        link if the graph is undirected."""
  723.         self.connect1(A, B, distance)
  724.         if not self.directed:
  725.             self.connect1(B, A, distance)
  726.  
  727.     def connect1(self, A, B, distance):
  728.         """Add a link from A to B of given distance, in one direction only."""
  729.         self.dict.setdefault(A, {})[B] = distance
  730.  
  731.     def get(self, a, b=None):
  732.         """Return a link distance or a dict of {node: distance} entries.
  733.        .get(a,b) returns the distance or None;
  734.        .get(a) returns a dict of {node: distance} entries, possibly {}."""
  735.         links = self.dict.setdefault(a, {})
  736.         if b is None:
  737.             return links
  738.         else:
  739.             return links.get(b)
  740.  
  741.     def nodes(self):
  742.         """Return a list of nodes in the graph."""
  743.         return list(self.dict.keys())
  744.  
  745.  
  746. def UndirectedGraph(dict=None):
  747.     """Build a Graph where every edge (including future ones) goes both ways."""
  748.     return Graph(dict=dict, directed=False)
  749.  
  750.  
  751. def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
  752.                 curvature=lambda: random.uniform(1.1, 1.5)):
  753.     """Construct a random graph, with the specified nodes, and random links.
  754.    The nodes are laid out randomly on a (width x height) rectangle.
  755.    Then each node is connected to the min_links nearest neighbors.
  756.    Because inverse links are added, some nodes will have more connections.
  757.    The distance between nodes is the hypotenuse times curvature(),
  758.    where curvature() defaults to a random number between 1.1 and 1.5."""
  759.     g = UndirectedGraph()
  760.     g.locations = {}
  761.     # Build the cities
  762.     for node in nodes:
  763.         g.locations[node] = (random.randrange(width), random.randrange(height))
  764.     # Build roads from each city to at least min_links nearest neighbors.
  765.     for i in range(min_links):
  766.         for node in nodes:
  767.             if len(g.get(node)) < min_links:
  768.                 here = g.locations[node]
  769.  
  770.                 def distance_to_node(n):
  771.                     if n is node or g.get(node, n):
  772.                         return infinity
  773.                     return distance(g.locations[n], here)
  774.                 neighbor = argmin(nodes, key=distance_to_node)
  775.                 d = distance(g.locations[neighbor], here) * curvature()
  776.                 g.connect(node, neighbor, int(d))
  777.     return g
  778.  
  779.    
  780. class GraphProblem(Problem):
  781.  
  782.     """The problem of searching a graph from one node to another."""
  783.  
  784.     def __init__(self, initial, goal, graph):
  785.         Problem.__init__(self, initial, goal)
  786.         self.graph = graph
  787.  
  788.     def actions(self, A):
  789.         """The actions at a graph node are just its neighbors."""
  790.         return list(self.graph.get(A).keys())
  791.  
  792.     def result(self, state, action):
  793.         """The result of going to a neighbor is just that neighbor."""
  794.         return action
  795.  
  796.     def path_cost(self, cost_so_far, A, action, B):
  797.         return cost_so_far + (self.graph.get(A, B) or infinity)
  798.  
  799.     # hevristika - broj na hopovi * cenata na rebroto so min vrednost
  800.     def h(self, node):
  801.         min_weight = min_cena(self.graph)
  802.         node=breadth_first_graph_search(GraphProblem(node.state, self.goal, self.graph))        
  803.         num_hops = len(node.solve())
  804.         return num_hops * min_weight
  805.  
  806.  
  807. germany_map = UndirectedGraph({
  808. "Frankfurt": {"Mannheim": 85, "Wurzburg": 217, "Kassel": 173},
  809. "Mannheim": {"Karlsruhe": 80},
  810. "Wurzburg": {"Erfurt": 186, "Nurnberg": 103},
  811. "Stuttgart": {"Nurnberg": 183},
  812. "Kassel": {"Munchen": 502},
  813. "Karlsruhe": {"Augsburg": 250},
  814. "Nurnberg": {"Munchen": 167},
  815. "Augsburg": {"Munchen": 84},  
  816. })
  817.  
  818. def min_cena(graph):
  819.     min_cena = infinity
  820.     for v in graph.dict.values():
  821.         for distance in v.values():
  822.             if distance < min_cena:
  823.                 min_cena = distance
  824.     return min_cena
  825.  
  826. germany_problem = GraphProblem(Pocetok, Kraj, germany_map)
  827. answer = astar_search(germany_problem).path_cost
  828. print answer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement