Advertisement
Nikolovska

[ВИ] лаб 2.2 Молекула

Jun 10th, 2018
1,136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 27.01 KB | None | 0 0
  1. """Неинформирано пребарување (2)
  2.  
  3. Молекула Problem 2 (0 / 0)
  4. Предложете соодветна репрезентација и напишете ги потребните функции во Python за да се реши следниот проблем за кој
  5. една можна почетна состојба е прикажана на слика 1:
  6.  
  7. enter image description here
  8.  
  9. Слика 1
  10.  
  11. “На табла 7x9 поставени се три атоми (внимавајте, двата H-атоми се различни: едниот има линк надолу, а другиот има линк
  12. нагоре). Полињата обоени во сива боја претставуваат препреки. Играчот може да ја започне играта со избирање на кој било
  13. од трите атоми. Играчот во секој момент произволно избира точно еден од трите атоми и го „турнува“ тој атом во една од
  14. четирите насоки: горе, долу, лево или десно. Движењето на „турнатиот“ атом продолжува во избраната насока се’ додека
  15. атомот не „удри“ во препрека или во некој друг атом (атомот секогаш застанува на првото поле што е соседно на препрека
  16. или на друг атом во соодветната насока). Целта на играта е атомите да се доведат во позиција во која ја формираат
  17. „молекулата“ прикажана десно од таблата. Играта завршува во моментот кога трите атоми ќе бидат поставени во бараната
  18. позиција, во произволни три соседни полиња од таблата. Не е возможно ротирање на атомите (линковите на атомите секогаш
  19. ќе бидат поставени како што се на почетокот на играта). Исто така, не е дозволено атомите да излегуваат од таблата.
  20. Потребно е проблемот да се реши во најмал број на потези.”
  21.  
  22. За сите тест примери изгледот и големината на таблата се исти како на примерот даден на сликата. За сите тест примери
  23. положбите на препреките се исти. За секој тест пример се менуваат почетните позиции на сите три атоми, соодветно.
  24.  
  25. Во рамки на почетниот код даден за задачата се вчитуваат влезните аргументи за секој тест пример. Во променливите
  26. H1AtomRedica и H1AtomKolona ги имате редицата и колоната во која на почетокот се наоѓа првиот H атом - со линк надолу
  27. (ако таблата ја гледате како матрица); во променливите ОAtomRedica и ОAtomKolona ги имате редицата и колоната во која на
  28. почетокот се наоѓа О атомот (ако таблата ја гледате како матрица); во променливите H2AtomRedica и H2AtomKolona ги имате
  29. редицата и колоната во која на почетокот се наоѓа вториот H атом - со линк нагоре (ако таблата ја гледате како матрица).
  30.  
  31. Движењата на атомите потребно е да ги именувате на следниот начин:
  32.  
  33. DesnoX - за придвижување на атомот X надесно (X може да биде H1, O или H2)
  34. LevoX - за придвижување на атомот X налево (X може да биде H1, O или H2)
  35. GoreX - за придвижување на атомот X нагоре (X може да биде H1, O или H2)
  36. DoluX - за придвижување на атомот X надолу (X може да биде H1, O или H2)
  37. Вашиот код треба да има само еден повик на функција за приказ на стандарден излез (print) со кој ќе ја вратите
  38. секвенцата на движења која треба да се направи за да може атомите од почетната позиција да се доведат до бараната
  39. позиција. Треба да примените неинформирано пребарување. Врз основа на тест примерите треба самите да определите кое
  40. пребарување ќе го користите.
  41.  
  42. Sample input
  43. 6
  44. 3
  45. 5
  46. 8
  47. 1
  48. 3
  49.  
  50. Sample output
  51. ['DesnoO', 'GoreO', 'LevoH2', 'DoluH2', 'LevoO', 'DoluO', 'GoreH1', 'LevoH1']
  52. """
  53.  
  54. # Python modul vo koj se implementirani algoritmite za neinformirano i informirano prebaruvanje
  55.  
  56. # ______________________________________________________________________________________________
  57. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  58.  
  59. import sys
  60. import bisect
  61.  
  62. infinity = float('inf')  # sistemski definirana vrednost za beskonecnost
  63.  
  64.  
  65. # ______________________________________________________________________________________________
  66. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  67.  
  68. class Queue:
  69.     """Queue is an abstract class/interface. There are three types:
  70.        Stack(): A Last In First Out Queue.
  71.        FIFOQueue(): A First In First Out Queue.
  72.        PriorityQueue(order, f): Queue in sorted order (default min-first).
  73.    Each type supports the following methods and functions:
  74.        q.append(item)  -- add an item to the queue
  75.        q.extend(items) -- equivalent to: for item in items: q.append(item)
  76.        q.pop()         -- return the top item from the queue
  77.        len(q)          -- number of items in q (also q.__len())
  78.        item in q       -- does q contain item?
  79.    Note that isinstance(Stack(), Queue) is false, because we implement stacks
  80.    as lists.  If Python ever gets interfaces, Queue will be an interface."""
  81.  
  82.     def __init__(self):
  83.         raise NotImplementedError
  84.  
  85.     def extend(self, items):
  86.         for item in items:
  87.             self.append(item)
  88.  
  89.  
  90. def Stack():
  91.     """A Last-In-First-Out Queue."""
  92.     return []
  93.  
  94.  
  95. class FIFOQueue(Queue):
  96.     """A First-In-First-Out Queue."""
  97.  
  98.     def __init__(self):
  99.         self.A = []
  100.         self.start = 0
  101.  
  102.     def append(self, item):
  103.         self.A.append(item)
  104.  
  105.     def __len__(self):
  106.         return len(self.A) - self.start
  107.  
  108.     def extend(self, items):
  109.         self.A.extend(items)
  110.  
  111.     def pop(self):
  112.         e = self.A[self.start]
  113.         self.start += 1
  114.         if self.start > 5 and self.start > len(self.A) / 2:
  115.             self.A = self.A[self.start:]
  116.             self.start = 0
  117.         return e
  118.  
  119.     def __contains__(self, item):
  120.         return item in self.A[self.start:]
  121.  
  122.  
  123. class PriorityQueue(Queue):
  124.     """A queue in which the minimum (or maximum) element (as determined by f and
  125.    order) is returned first. If order is min, the item with minimum f(x) is
  126.    returned first; if order is max, then it is the item with maximum f(x).
  127.    Also supports dict-like lookup. This structure will be most useful in informed searches"""
  128.  
  129.     def __init__(self, order=min, f=lambda x: x):
  130.         self.A = []
  131.         self.order = order
  132.         self.f = f
  133.  
  134.     def append(self, item):
  135.         bisect.insort(self.A, (self.f(item), item))
  136.  
  137.     def __len__(self):
  138.         return len(self.A)
  139.  
  140.     def pop(self):
  141.         if self.order == min:
  142.             return self.A.pop(0)[1]
  143.         else:
  144.             return self.A.pop()[1]
  145.  
  146.     def __contains__(self, item):
  147.         return any(item == pair[1] for pair in self.A)
  148.  
  149.     def __getitem__(self, key):
  150.         for _, item in self.A:
  151.             if item == key:
  152.                 return item
  153.  
  154.     def __delitem__(self, key):
  155.         for i, (value, item) in enumerate(self.A):
  156.             if item == key:
  157.                 self.A.pop(i)
  158.  
  159.  
  160. # ______________________________________________________________________________________________
  161. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  162. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  163. # na sekoj eden problem sto sakame da go resime
  164.  
  165.  
  166. class Problem:
  167.     """The abstract class for a formal problem.  You should subclass this and
  168.    implement the method successor, and possibly __init__, goal_test, and
  169.    path_cost. Then you will create instances of your subclass and solve them
  170.    with the various search functions."""
  171.  
  172.     def __init__(self, initial, goal=None):
  173.         """The constructor specifies the initial state, and possibly a goal
  174.        state, if there is a unique goal.  Your subclass's constructor can add
  175.        other arguments."""
  176.         self.initial = initial
  177.         self.goal = goal
  178.  
  179.     def successor(self, state):
  180.         """Given a state, return a dictionary of {action : state} pairs reachable
  181.        from this state. If there are many successors, consider an iterator
  182.        that yields the successors one at a time, rather than building them
  183.        all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  184.         raise NotImplementedError
  185.  
  186.     def actions(self, state):
  187.         """Given a state, return a list of all actions possible from that state"""
  188.         raise NotImplementedError
  189.  
  190.     def result(self, state, action):
  191.         """Given a state and action, return the resulting state"""
  192.         raise NotImplementedError
  193.  
  194.     def goal_test(self, state):
  195.         """Return True if the state is a goal. The default method compares the
  196.        state to self.goal, as specified in the constructor. Implement this
  197.        method if checking against a single self.goal is not enough."""
  198.         return state == self.goal
  199.  
  200.     def path_cost(self, c, state1, action, state2):
  201.         """Return the cost of a solution path that arrives at state2 from
  202.        state1 via action, assuming cost c to get up to state1. If the problem
  203.        is such that the path doesn't matter, this function will only look at
  204.        state2.  If the path does matter, it will consider c and maybe state1
  205.        and action. The default method costs 1 for every step in the path."""
  206.         return c + 1
  207.  
  208.     def value(self):
  209.         """For optimization problems, each state has a value.  Hill-climbing
  210.        and related algorithms try to maximize this value."""
  211.         raise NotImplementedError
  212.  
  213.  
  214. # ______________________________________________________________________________
  215. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  216. # Klasata Node ne se nasleduva
  217.  
  218. class Node:
  219.     """A node in a search tree. Contains a pointer to the parent (the node
  220.    that this is a successor of) and to the actual state for this node. Note
  221.    that if a state is arrived at by two paths, then there are two nodes with
  222.    the same state.  Also includes the action that got us to this state, and
  223.    the total path_cost (also known as g) to reach the node.  Other functions
  224.    may add an f and h value; see best_first_graph_search and astar_search for
  225.    an explanation of how the f and h values are handled. You will not need to
  226.    subclass this class."""
  227.  
  228.     def __init__(self, state, parent=None, action=None, path_cost=0):
  229.         "Create a search tree Node, derived from a parent by an action."
  230.         self.state = state
  231.         self.parent = parent
  232.         self.action = action
  233.         self.path_cost = path_cost
  234.         self.depth = 0
  235.         if parent:
  236.             self.depth = parent.depth + 1
  237.  
  238.     def __repr__(self):
  239.         return "<Node %s>" % (self.state,)
  240.  
  241.     def __lt__(self, node):
  242.         return self.state < node.state
  243.  
  244.     def expand(self, problem):
  245.         "List the nodes reachable in one step from this node."
  246.         return [self.child_node(problem, action)
  247.                 for action in problem.actions(self.state)]
  248.  
  249.     def child_node(self, problem, action):
  250.         "Return a child node from this node"
  251.         next = problem.result(self.state, action)
  252.         return Node(next, self, action,
  253.                     problem.path_cost(self.path_cost, self.state,
  254.                                       action, next))
  255.  
  256.     def solution(self):
  257.         "Return the sequence of actions to go from the root to this node."
  258.         return [node.action for node in self.path()[1:]]
  259.  
  260.     def solve(self):
  261.         "Return the sequence of states to go from the root to this node."
  262.         return [node.state for node in self.path()[0:]]
  263.  
  264.     def path(self):
  265.         "Return a list of nodes forming the path from the root to this node."
  266.         x, result = self, []
  267.         while x:
  268.             result.append(x)
  269.             x = x.parent
  270.         return list(reversed(result))
  271.  
  272.     # We want for a queue of nodes in breadth_first_search or
  273.     # astar_search to have no duplicated states, so we treat nodes
  274.     # with the same state as equal. [Problem: this may not be what you
  275.     # want in other contexts.]
  276.  
  277.     def __eq__(self, other):
  278.         return isinstance(other, Node) and self.state == other.state
  279.  
  280.     def __hash__(self):
  281.         return hash(self.state)
  282.  
  283.  
  284. # ________________________________________________________________________________________________________
  285. # Neinformirano prebaruvanje vo ramki na drvo
  286. # Vo ramki na drvoto ne razresuvame jamki
  287.  
  288. def tree_search(problem, fringe):
  289.     """Search through the successors of a problem to find a goal.
  290.    The argument fringe should be an empty queue."""
  291.     fringe.append(Node(problem.initial))
  292.     while fringe:
  293.         node = fringe.pop()
  294.         print(node.state)
  295.         if problem.goal_test(node.state):
  296.             return node
  297.         fringe.extend(node.expand(problem))
  298.     return None
  299.  
  300.  
  301. def breadth_first_tree_search(problem):
  302.     "Search the shallowest nodes in the search tree first."
  303.     return tree_search(problem, FIFOQueue())
  304.  
  305.  
  306. def depth_first_tree_search(problem):
  307.     "Search the deepest nodes in the search tree first."
  308.     return tree_search(problem, Stack())
  309.  
  310.  
  311. # ________________________________________________________________________________________________________
  312. # Neinformirano prebaruvanje vo ramki na graf
  313. # Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  314.  
  315. def graph_search(problem, fringe):
  316.     """Search through the successors of a problem to find a goal.
  317.    The argument fringe should be an empty queue.
  318.    If two paths reach a state, only use the best one."""
  319.     closed = {}
  320.     fringe.append(Node(problem.initial))
  321.     while fringe:
  322.         node = fringe.pop()
  323.         if problem.goal_test(node.state):
  324.             return node
  325.         if node.state not in closed:
  326.             closed[node.state] = True
  327.             fringe.extend(node.expand(problem))
  328.     return None
  329.  
  330.  
  331. def breadth_first_graph_search(problem):
  332.     "Search the shallowest nodes in the search tree first."
  333.     return graph_search(problem, FIFOQueue())
  334.  
  335.  
  336. def depth_first_graph_search(problem):
  337.     "Search the deepest nodes in the search tree first."
  338.     return graph_search(problem, Stack())
  339.  
  340.  
  341. def uniform_cost_search(problem):
  342.     "Search the nodes in the search tree with lowest cost first."
  343.     return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  344.  
  345.  
  346. def depth_limited_search(problem, limit=50):
  347.     "depth first search with limited depth"
  348.  
  349.     def recursive_dls(node, problem, limit):
  350.         "helper function for depth limited"
  351.         cutoff_occurred = False
  352.         if problem.goal_test(node.state):
  353.             return node
  354.         elif node.depth == limit:
  355.             return 'cutoff'
  356.         else:
  357.             for successor in node.expand(problem):
  358.                 result = recursive_dls(successor, problem, limit)
  359.                 if result == 'cutoff':
  360.                     cutoff_occurred = True
  361.                 elif result != None:
  362.                     return result
  363.         if cutoff_occurred:
  364.             return 'cutoff'
  365.         else:
  366.             return None
  367.  
  368.     # Body of depth_limited_search:
  369.     return recursive_dls(Node(problem.initial), problem, limit)
  370.  
  371.  
  372. def iterative_deepening_search(problem):
  373.     for depth in range(sys.maxint):
  374.         result = depth_limited_search(problem, depth)
  375.         if result is not 'cutoff':
  376.             return result
  377.  
  378.  
  379. # _________________________________________________________________________________________________________
  380. # PRIMER 1 : PROBLEM SO DVA SADA SO VODA
  381. # OPIS: Dadeni se dva sada J0 i J1 so kapaciteti C0 i C1
  382. # Na pocetok dvata sada se polni. Inicijalnata sostojba moze da se prosledi na pocetok
  383. # Problemot e kako da se stigne do sostojba vo koja J0 ke ima G0 litri, a J1 ke ima G1 litri
  384. # AKCII: 1. Da se isprazni bilo koj od sadovite
  385. # 2. Da se prefrli tecnosta od eden sad vo drug so toa sto ne moze da se nadmine kapacitetot na sadovite
  386. # Moze da ima i opcionalen tret vid na akcii 3. Napolni bilo koj od sadovite (studentite da ja implementiraat ovaa varijanta)
  387. # ________________________________________________________________________________________________________
  388.  
  389. class WJ(Problem):
  390.     """STATE: Torka od oblik (3,2) if jug J0 has 3 liters and J1 2 liters
  391.    Opcionalno moze za nekoj od sadovite da se sretne i vrednost '*' sto znaci deka e nebitno kolku ima vo toj sad
  392.    GOAL: Predefinirana sostojba do kade sakame da stigneme. Ako ne interesira samo eden sad za drugiot mozeme da stavime '*'
  393.    PROBLEM: Se specificiraat kapacitetite na sadovite, pocetna sostojba i cel """
  394.  
  395.     def __init__(self, capacities=(5, 2), initial=(5, 0), goal=(0, 1)):
  396.         self.capacities = capacities
  397.         self.initial = initial
  398.         self.goal = goal
  399.  
  400.     def goal_test(self, state):
  401.         """ Vraka true ako sostojbata e celna """
  402.         g = self.goal
  403.         return (state[0] == g[0] or g[0] == '*') and \
  404.                (state[1] == g[1] or g[1] == '*')
  405.  
  406.     def successor(self, J):
  407.         """Vraka recnik od sledbenici na sostojbata"""
  408.         successors = dict()
  409.         J0, J1 = J
  410.         (C0, C1) = self.capacities
  411.         if J0 > 0:
  412.             Jnew = 0, J1
  413.             successors['dump jug 0'] = Jnew
  414.         if J1 > 0:
  415.             Jnew = J0, 0
  416.             successors['dump jug 1'] = Jnew
  417.         if J1 < C1 and J0 > 0:
  418.             delta = min(J0, C1 - J1)
  419.             Jnew = J0 - delta, J1 + delta
  420.             successors['pour jug 0 into jug 1'] = Jnew
  421.         if J0 < C0 and J1 > 0:
  422.             delta = min(J1, C0 - J0)
  423.             Jnew = J0 + delta, J1 - delta
  424.             successors['pour jug 1 into jug 0'] = Jnew
  425.         return successors
  426.  
  427.     def actions(self, state):
  428.         return self.successor(state).keys()
  429.  
  430.     def result(self, state, action):
  431.         possible = self.successor(state)
  432.         return possible[action]
  433.  
  434.  
  435. # So vaka definiraniot problem mozeme da gi koristime site neinformirani prebaruvanja
  436. # Vo prodolzenie se dadeni mozni povici (vnimavajte za da moze da napravite povik mora da definirate problem)
  437. #
  438. #    WJInstance = WJ((5, 2), (5, 2), ('*', 1))
  439. #    print WJInstance
  440. #
  441. #    answer1 = breadth_first_tree_search(WJInstance)
  442. #    print answer1.solve()
  443. #
  444. #    answer2 = depth_first_tree_search(WJInstance) #vnimavajte na ovoj povik, moze da vleze vo beskonecna jamka
  445. #    print answer2.solve()
  446. #
  447. #    answer3 = breadth_first_graph_search(WJInstance)
  448. #    print answer3.solve()
  449. #
  450. #    answer4 = depth_first_graph_search(WJInstance)
  451. #    print answer4.solve()
  452. #
  453. #    answer5 = depth_limited_search(WJInstance)
  454. #    print answer5.solve()
  455. #
  456. #    answer6 = iterative_deepening_search(WJInstance)
  457. #    print answer6.solve()
  458.  
  459.  
  460.  
  461. # Vasiot kod pisuvajte go pod ovoj komentar
  462.  
  463. prepreki = [(1, 4), (1, 6), (1, 8), (2, 3), (2, 9), (4, 2), (4, 7), (4, 8), (5, 5), (5, 7), (6, 1), (6, 2), (6, 4),
  464.             (6, 7)]
  465.  
  466.  
  467. def gore_atom_h1(a):
  468.     h1 = a[0]
  469.     while 0 < h1[0] < 8 and 0 < h1[1] < 10 and ((h1[0], h1[1]) not in prepreki) and (
  470.             (h1[0], h1[1]) not in (a[1], a[2])):
  471.         h1 = a[0]
  472.         x = h1[0]
  473.         x = x - 1
  474.         a = (x, h1[1]), a[1], a[2]
  475.     a_new = (h1[0] + 1, h1[1])  # +1 (a ne -1) poradi toa sto go vrakjame a[0] vo dozvolenata sostojba
  476.     # a_new = a[0] - 1, a[1]
  477.     return a_new
  478.  
  479.  
  480. def dolu_atom_h1(a):
  481.     h1 = a[0]
  482.     while 0 < h1[0] < 8 and 0 < h1[1] < 10 and ((h1[0], h1[1]) not in prepreki) and (
  483.             (h1[0], h1[1]) not in (a[1], a[2])):
  484.         h1 = a[0]
  485.         x = h1[0]
  486.         x = x + 1
  487.         a = (x, h1[1]), a[1], a[2]
  488.     a_new = (h1[0] - 1, h1[1])  
  489.     return a_new
  490.  
  491.  
  492. def levo_atom_h1(a):
  493.     h1 = a[0]
  494.     while 0 < h1[0] < 8 and 0 < h1[1] < 10 and ((h1[0], h1[1]) not in prepreki) and (
  495.             (h1[0], h1[1]) not in (a[1], a[2])):
  496.         h1 = a[0]
  497.         y = h1[1]
  498.         y = y - 1
  499.         a = (h1[0], y), a[1], a[2]
  500.     a_new = (h1[0], h1[1] + 1)
  501.     return a_new
  502.  
  503.  
  504. def desno_atom_h1(a):
  505.     h1 = a[0]
  506.     while 0 < h1[0] < 8 and 0 < h1[1] < 10 and ((h1[0], h1[1]) not in prepreki) and (
  507.             (h1[0], h1[1]) not in (a[1], a[2])):
  508.         h1 = a[0]
  509.         y = h1[1]
  510.         y = y + 1
  511.         a = (h1[0], y), a[1], a[2]
  512.     a_new = (h1[0], h1[1] - 1)
  513.     return a_new
  514.  
  515.  
  516. def gore_atom_o(a):
  517.     o = a[1]
  518.     while 0 < o[0] < 8 and 0 < o[1] < 10 and ((o[0], o[1]) not in prepreki) and (
  519.             (o[0], o[1]) not in (a[0], a[2])):
  520.         o = a[1]
  521.         x = o[0]
  522.         x = x - 1
  523.         a = a[0], (x, o[1]), a[2]
  524.     a_new = (o[0] + 1, o[1])
  525.     return a_new
  526.  
  527.  
  528. def dolu_atom_o(a):
  529.     o = a[1]
  530.     while 0 < o[0] < 8 and 0 < o[1] < 10 and ((o[0], o[1]) not in prepreki) and (
  531.             (o[0], o[1]) not in (a[0], a[2])):
  532.         o = a[1]
  533.         x = o[0]
  534.         x = x + 1
  535.         a = a[0], (x, o[1]), a[2]
  536.     a_new = (o[0] - 1, o[1])
  537.     return a_new
  538.  
  539.  
  540. def levo_atom_o(a):
  541.     o = a[1]
  542.     while 0 < o[0] < 8 and 0 < o[1] < 10 and ((o[0], o[1]) not in prepreki) and (
  543.             (o[0], o[1]) not in (a[0], a[2])):
  544.         o = a[1]
  545.         y = o[1]
  546.         y = y - 1
  547.         a = a[0], (o[0], y), a[2]
  548.     a_new = (o[0], o[1] + 1)
  549.     return a_new
  550.  
  551.  
  552. def desno_atom_o(a):
  553.     o = a[1]
  554.     while 0 < o[0] < 8 and 0 < o[1] < 10 and ((o[0], o[1]) not in prepreki) and (
  555.             (o[0], o[1]) not in (a[0], a[2])):
  556.         o = a[1]
  557.         y = o[1]
  558.         y = y + 1
  559.         a = a[0], (o[0], y), a[2]
  560.     a_new = (o[0], o[1] - 1)
  561.     return a_new
  562.  
  563.  
  564. def gore_atom_h2(a):
  565.     h2 = a[2]
  566.     while 0 < h2[0] < 8 and 0 < h2[1] < 10 and ((h2[0], h2[1]) not in prepreki) and (
  567.             (h2[0], h2[1]) not in (a[0], a[1])):
  568.         h2 = a[2]
  569.         x = h2[0]
  570.         x = x - 1
  571.         a = a[0], a[1], (x, h2[1])
  572.     a_new = (h2[0] + 1, h2[1])
  573.     return a_new
  574.  
  575.  
  576. def dolu_atom_h2(a):
  577.     h2 = a[2]
  578.     while 0 < h2[0] < 8 and 0 < h2[1] < 10 and ((h2[0], h2[1]) not in prepreki) and (
  579.             (h2[0], h2[1]) not in (a[0], a[1])):
  580.         h2 = a[2]
  581.         x = h2[0]
  582.         x = x + 1
  583.         a = a[0], a[1], (x, h2[1])
  584.     a_new = (h2[0] - 1, h2[1])
  585.     return a_new
  586.  
  587.  
  588. def levo_atom_h2(a):
  589.     h2 = a[2]
  590.     while 0 < h2[0] < 8 and 0 < h2[1] < 10 and ((h2[0], h2[1]) not in prepreki) and (
  591.             (h2[0], h2[1]) not in (a[0], a[1])):
  592.         h2 = a[2]
  593.         y = h2[1]
  594.         y = y - 1
  595.         a = a[0], a[1], (h2[0], y)
  596.     a_new = (h2[0], h2[1] + 1)
  597.     return a_new
  598.  
  599.  
  600. def desno_atom_h2(a):
  601.     h2 = a[2]
  602.     while 0 < h2[0] < 8 and 0 < h2[1] < 10 and ((h2[0], h2[1]) not in prepreki) and (
  603.             (h2[0], h2[1]) not in (a[0], a[1])):
  604.         h2 = a[2]
  605.         y = h2[1]
  606.         y = y + 1
  607.         a = a[0], a[1], (h2[0], y)
  608.     a_new = (h2[0], h2[1] - 1)
  609.     return a_new
  610.  
  611.  
  612. class Molekula(Problem):
  613.  
  614.     def __init__(self, initial=((0, 0), (1, 1), (2, 2))):
  615.         self.initial = initial
  616.  
  617.     def goal_test(self, state):
  618.         """ Vraka true ako sostojbata e celna """    # site treba da se vo ista kolona, vo redici edna ispod druga
  619.         h1 = state[0]
  620.         o = state[1]
  621.         h2 = state[2]
  622.         return h1[1] == o[1] and o[1] == h2[1] and h1[0] == o[0] - 1 and o[0] == h2[0] - 1
  623.  
  624.     def successor(self, state):
  625.         """Vraka recnik od sledbenici na sostojbata"""
  626.         successors = dict()
  627.  
  628.         h1 = state[0]
  629.         o = state[1]
  630.         h2 = state[2]
  631.  
  632.         #Gore h1
  633.         h1_new = gore_atom_h1(state)
  634.         state_new = (h1_new, o, h2)
  635.         successors['GoreH1'] = state_new
  636.  
  637.         # Dolu h1
  638.         h1_new = dolu_atom_h1(state)
  639.         state_new = (h1_new, o, h2)
  640.         successors['DoluH1'] = state_new
  641.  
  642.         # Levo h1
  643.         h1_new = levo_atom_h1(state)
  644.         state_new = (h1_new, o, h2)
  645.         successors['LevoH1'] = state_new
  646.  
  647.         # Desno h1
  648.         h1_new = desno_atom_h1(state)
  649.         state_new = (h1_new, o, h2)
  650.         successors['DesnoH1'] = state_new
  651.  
  652.         # Gore o
  653.         o_new = gore_atom_o(state)
  654.         state_new = (h1, o_new, h2)
  655.         successors['GoreO'] = state_new
  656.  
  657.         # Dolu o
  658.         o_new = dolu_atom_o(state)
  659.         state_new = (h1, o_new, h2)
  660.         successors['DoluO'] = state_new
  661.  
  662.         # Levo o
  663.         o_new = levo_atom_o(state)
  664.         state_new = (h1, o_new, h2)
  665.         successors['LevoO'] = state_new
  666.  
  667.         # Desno o
  668.         o_new = desno_atom_o(state)
  669.         state_new = (h1, o_new, h2)
  670.         successors['DesnoO'] = state_new
  671.  
  672.         # Gore h2
  673.         h2_new = gore_atom_h2(state)
  674.         state_new = (h1, o, h2_new)
  675.         successors['GoreH2'] = state_new
  676.  
  677.         # Dolu h2
  678.         h2_new = dolu_atom_h2(state)
  679.         state_new = (h1, o, h2_new)
  680.         successors['DoluH2'] = state_new
  681.  
  682.         # Levo h2
  683.         h2_new = levo_atom_h2(state)
  684.         state_new = (h1, o, h2_new)
  685.         successors['LevoH2'] = state_new
  686.  
  687.         # Desno h2
  688.         h2_new = desno_atom_h2(state)
  689.         state_new = (h1, o, h2_new)
  690.         successors['DesnoH2'] = state_new
  691.  
  692.         return successors
  693.  
  694.     def actions(self, state):
  695.         return self.successor(state).keys()
  696.  
  697.     def result(self, state, action):
  698.         possible = self.successor(state)
  699.         return possible[action]
  700.  
  701.  
  702. # Vcituvanje na vleznite argumenti za test primerite
  703.  
  704. H1AtomRedica = int(input())
  705. H1AtomKolona = int(input())
  706. OAtomRedica = int(input())
  707. OAtomKolona = int(input())
  708. H2AtomRedica = int(input())
  709. H2AtomKolona = int(input())
  710.  
  711. MolekulaInstance = Molekula(((H1AtomRedica, H1AtomKolona), (OAtomRedica, OAtomKolona), (H2AtomRedica, H2AtomKolona)))
  712.  
  713. answer = breadth_first_graph_search(MolekulaInstance)
  714. print(answer.solution())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement