SHARE
TWEET

Untitled

a guest Apr 19th, 2019 91 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Python modul vo koj se implementirani algoritmite za neinformirano i informirano prebaruvanje
  2.  
  3. # ______________________________________________________________________________________________
  4. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  5.  
  6. import sys
  7. import bisect
  8.  
  9. from math import sqrt
  10.  
  11. infinity = float('inf')  # sistemski definirana vrednost za beskonecnost
  12.  
  13.  
  14. # ______________________________________________________________________________________________
  15. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  16.  
  17. class Queue:
  18.     """Queue is an abstract class/interface. There are three types:
  19.         Stack(): A Last In First Out Queue.
  20.         FIFOQueue(): A First In First Out Queue.
  21.         PriorityQueue(order, f): Queue in sorted order (default min-first).
  22.     Each type supports the following methods and functions:
  23.         q.append(item)  -- add an item to the queue
  24.         q.extend(items) -- equivalent to: for item in items: q.append(item)
  25.         q.pop()         -- return the top item from the queue
  26.         len(q)          -- number of items in q (also q.__len())
  27.         item in q       -- does q contain item?
  28.     Note that isinstance(Stack(), Queue) is false, because we implement stacks
  29.     as lists.  If Python ever gets interfaces, Queue will be an interface."""
  30.  
  31.     def __init__(self):
  32.         raise NotImplementedError
  33.  
  34.     def extend(self, items):
  35.         for item in items:
  36.             self.append(item)
  37.  
  38.  
  39. def Stack():
  40.     """A Last-In-First-Out Queue."""
  41.     return []
  42.  
  43.  
  44. class FIFOQueue(Queue):
  45.     """A First-In-First-Out Queue."""
  46.  
  47.     def __init__(self):
  48.         self.A = []
  49.         self.start = 0
  50.  
  51.     def append(self, item):
  52.         self.A.append(item)
  53.  
  54.     def __len__(self):
  55.         return len(self.A) - self.start
  56.  
  57.     def extend(self, items):
  58.         self.A.extend(items)
  59.  
  60.     def pop(self):
  61.         e = self.A[self.start]
  62.         self.start += 1
  63.         if self.start > 5 and self.start > len(self.A) / 2:
  64.             self.A = self.A[self.start:]
  65.             self.start = 0
  66.         return e
  67.  
  68.     def __contains__(self, item):
  69.         return item in self.A[self.start:]
  70.  
  71.  
  72. class PriorityQueue(Queue):
  73.     """A queue in which the minimum (or maximum) element (as determined by f and
  74.     order) is returned first. If order is min, the item with minimum f(x) is
  75.     returned first; if order is max, then it is the item with maximum f(x).
  76.     Also supports dict-like lookup. This structure will be most useful in informed searches"""
  77.  
  78.     def __init__(self, order=min, f=lambda x: x):
  79.         self.A = []
  80.         self.order = order
  81.         self.f = f
  82.  
  83.     def append(self, item):
  84.         bisect.insort(self.A, (self.f(item), item))
  85.  
  86.     def __len__(self):
  87.         return len(self.A)
  88.  
  89.     def pop(self):
  90.         if self.order == min:
  91.             return self.A.pop(0)[1]
  92.         else:
  93.             return self.A.pop()[1]
  94.  
  95.     def __contains__(self, item):
  96.         return any(item == pair[1] for pair in self.A)
  97.  
  98.     def __getitem__(self, key):
  99.         for _, item in self.A:
  100.             if item == key:
  101.                 return item
  102.  
  103.     def __delitem__(self, key):
  104.         for i, (value, item) in enumerate(self.A):
  105.             if item == key:
  106.                 self.A.pop(i)
  107.  
  108.  
  109. # ______________________________________________________________________________________________
  110. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  111. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  112. # na sekoj eden problem sto sakame da go resime
  113.  
  114.  
  115. class Problem:
  116.     """The abstract class for a formal problem.  You should subclass this and
  117.     implement the method successor, and possibly __init__, goal_test, and
  118.     path_cost. Then you will create instances of your subclass and solve them
  119.     with the various search functions."""
  120.  
  121.     def __init__(self, initial, goal=None):
  122.         """The constructor specifies the initial state, and possibly a goal
  123.         state, if there is a unique goal.  Your subclass's constructor can add
  124.         other arguments."""
  125.         self.initial = initial
  126.         self.goal = goal
  127.  
  128.     def successor(self, state):
  129.         """Given a state, return a dictionary of {action : state} pairs reachable
  130.         from this state. If there are many successors, consider an iterator
  131.         that yields the successors one at a time, rather than building them
  132.         all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  133.         raise NotImplementedError
  134.  
  135.     def actions(self, state):
  136.         """Given a state, return a list of all actions possible from that state"""
  137.         raise NotImplementedError
  138.  
  139.     def result(self, state, action):
  140.         """Given a state and action, return the resulting state"""
  141.         raise NotImplementedError
  142.  
  143.     def goal_test(self, state):
  144.         """Return True if the state is a goal. The default method compares the
  145.         state to self.goal, as specified in the constructor. Implement this
  146.         method if checking against a single self.goal is not enough."""
  147.         return state == self.goal
  148.  
  149.     def path_cost(self, c, state1, action, state2):
  150.         """Return the cost of a solution path that arrives at state2 from
  151.         state1 via action, assuming cost c to get up to state1. If the problem
  152.         is such that the path doesn't matter, this function will only look at
  153.         state2.  If the path does matter, it will consider c and maybe state1
  154.         and action. The default method costs 1 for every step in the path."""
  155.         return c + 1
  156.  
  157.     def value(self):
  158.         """For optimization problems, each state has a value.  Hill-climbing
  159.         and related algorithms try to maximize this value."""
  160.         raise NotImplementedError
  161.  
  162.  
  163. # ______________________________________________________________________________
  164. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  165. # Klasata Node ne se nasleduva
  166.  
  167. class Node:
  168.     """A node in a search tree. Contains a pointer to the parent (the node
  169.     that this is a successor of) and to the actual state for this node. Note
  170.     that if a state is arrived at by two paths, then there are two nodes with
  171.     the same state.  Also includes the action that got us to this state, and
  172.     the total path_cost (also known as g) to reach the node.  Other functions
  173.     may add an f and h value; see best_first_graph_search and astar_search for
  174.     an explanation of how the f and h values are handled. You will not need to
  175.     subclass this class."""
  176.  
  177.     def __init__(self, state, parent=None, action=None, path_cost=0):
  178.         "Create a search tree Node, derived from a parent by an action."
  179.         self.state = state
  180.         self.parent = parent
  181.         self.action = action
  182.         self.path_cost = path_cost
  183.         self.depth = 0
  184.         if parent:
  185.             self.depth = parent.depth + 1
  186.  
  187.     def __repr__(self):
  188.         return "<Node %s>" % (self.state,)
  189.  
  190.     def __lt__(self, node):
  191.         return self.state < node.state
  192.  
  193.     def expand(self, problem):
  194.         "List the nodes reachable in one step from this node."
  195.         return [self.child_node(problem, action)
  196.                 for action in problem.actions(self.state)]
  197.  
  198.     def child_node(self, problem, action):
  199.         "Return a child node from this node"
  200.         next = problem.result(self.state, action)
  201.         return Node(next, self, action,
  202.                     problem.path_cost(self.path_cost, self.state,
  203.                                       action, next))
  204.  
  205.     def solution(self):
  206.         "Return the sequence of actions to go from the root to this node."
  207.         return [node.action for node in self.path()[1:]]
  208.  
  209.     def solve(self):
  210.         "Return the sequence of states to go from the root to this node."
  211.         return [node.state for node in self.path()[0:]]
  212.  
  213.     def path(self):
  214.         "Return a list of nodes forming the path from the root to this node."
  215.         x, result = self, []
  216.         while x:
  217.             result.append(x)
  218.             x = x.parent
  219.         return list(reversed(result))
  220.  
  221.     # We want for a queue of nodes in breadth_first_search or
  222.     # astar_search to have no duplicated states, so we treat nodes
  223.     # with the same state as equal. [Problem: this may not be what you
  224.     # want in other contexts.]
  225.  
  226.     def __eq__(self, other):
  227.         return isinstance(other, Node) and self.state == other.state
  228.  
  229.     def __hash__(self):
  230.         return hash(self.state)
  231.  
  232.  
  233. # ________________________________________________________________________________________________________
  234. # Neinformirano prebaruvanje vo ramki na drvo
  235. # Vo ramki na drvoto ne razresuvame jamki
  236.  
  237. def tree_search(problem, fringe):
  238.     """Search through the successors of a problem to find a goal.
  239.     The argument fringe should be an empty queue."""
  240.     fringe.append(Node(problem.initial))
  241.     while fringe:
  242.         node = fringe.pop()
  243.         print(node.state)
  244.         if problem.goal_test(node.state):
  245.             return node
  246.         fringe.extend(node.expand(problem))
  247.     return None
  248.  
  249.  
  250. def breadth_first_tree_search(problem):
  251.     "Search the shallowest nodes in the search tree first."
  252.     return tree_search(problem, FIFOQueue())
  253.  
  254.  
  255. def depth_first_tree_search(problem):
  256.     "Search the deepest nodes in the search tree first."
  257.     return tree_search(problem, Stack())
  258.  
  259.  
  260. # ________________________________________________________________________________________________________
  261. # Neinformirano prebaruvanje vo ramki na graf
  262. # Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  263.  
  264. def graph_search(problem, fringe):
  265.     """Search through the successors of a problem to find a goal.
  266.     The argument fringe should be an empty queue.
  267.     If two paths reach a state, only use the best one."""
  268.     closed = {}
  269.     fringe.append(Node(problem.initial))
  270.     while fringe:
  271.         node = fringe.pop()
  272.         if problem.goal_test(node.state):
  273.             return node
  274.         if node.state not in closed:
  275.             closed[node.state] = True
  276.             fringe.extend(node.expand(problem))
  277.     return None
  278.  
  279.  
  280. def breadth_first_graph_search(problem):
  281.     "Search the shallowest nodes in the search tree first."
  282.     return graph_search(problem, FIFOQueue())
  283.  
  284.  
  285. def depth_first_graph_search(problem):
  286.     "Search the deepest nodes in the search tree first."
  287.     return graph_search(problem, Stack())
  288.  
  289.  
  290. def uniform_cost_search(problem):
  291.     "Search the nodes in the search tree with lowest cost first."
  292.     return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  293.  
  294.  
  295. def depth_limited_search(problem, limit=50):
  296.     "depth first search with limited depth"
  297.  
  298.     def recursive_dls(node, problem, limit):
  299.         "helper function for depth limited"
  300.         cutoff_occurred = False
  301.         if problem.goal_test(node.state):
  302.             return node
  303.         elif node.depth == limit:
  304.             return 'cutoff'
  305.         else:
  306.             for successor in node.expand(problem):
  307.                 result = recursive_dls(successor, problem, limit)
  308.                 if result == 'cutoff':
  309.                     cutoff_occurred = True
  310.                 elif result != None:
  311.                     return result
  312.         if cutoff_occurred:
  313.             return 'cutoff'
  314.         else:
  315.             return None
  316.  
  317.     # Body of depth_limited_search:
  318.     return recursive_dls(Node(problem.initial), problem, limit)
  319.  
  320.  
  321. def iterative_deepening_search(problem):
  322.     for depth in xrange(sys.maxint):
  323.         result = depth_limited_search(problem, depth)
  324.         if result is not 'cutoff':
  325.             return result
  326.  
  327.  
  328. # _________________________________________________________________________________________________________
  329. # PRIMER 1 : PROBLEM SO DVA SADA SO VODA
  330. # OPIS: Dadeni se dva sada J0 i J1 so kapaciteti C0 i C1
  331. # Na pocetok dvata sada se polni. Inicijalnata sostojba moze da se prosledi na pocetok
  332. # Problemot e kako da se stigne do sostojba vo koja J0 ke ima G0 litri, a J1 ke ima G1 litri
  333. # AKCII: 1. Da se isprazni bilo koj od sadovite
  334. # 2. Da se prefrli tecnosta od eden sad vo drug so toa sto ne moze da se nadmine kapacitetot na sadovite
  335. # Moze da ima i opcionalen tret vid na akcii 3. Napolni bilo koj od sadovite (studentite da ja implementiraat ovaa varijanta)
  336. # ________________________________________________________________________________________________________
  337.  
  338. class WJ(Problem):
  339.     """STATE: Torka od oblik (3,2) if jug J0 has 3 liters and J1 2 liters
  340.     Opcionalno moze za nekoj od sadovite da se sretne i vrednost '*' sto znaci deka e nebitno kolku ima vo toj sad
  341.     GOAL: Predefinirana sostojba do kade sakame da stigneme. Ako ne interesira samo eden sad za drugiot mozeme da stavime '*'
  342.     PROBLEM: Se specificiraat kapacitetite na sadovite, pocetna sostojba i cel """
  343.  
  344.     def __init__(self, capacities=(5, 2), initial=(5, 0), goal=(0, 1)):
  345.         self.capacities = capacities
  346.         self.initial = initial
  347.         self.goal = goal
  348.  
  349.     def goal_test(self, state):
  350.         """ Vraka true ako sostojbata e celna """
  351.         g = self.goal
  352.         return (state[0] == g[0] or g[0] == '*') and \
  353.                (state[1] == g[1] or g[1] == '*')
  354.  
  355.     def successor(self, J):
  356.         """Vraka recnik od sledbenici na sostojbata"""
  357.         successors = dict()
  358.         J0, J1 = J
  359.         (C0, C1) = self.capacities
  360.         if J0 > 0:
  361.             Jnew = 0, J1
  362.             successors['dump jug 0'] = Jnew
  363.         if J1 > 0:
  364.             Jnew = J0, 0
  365.             successors['dump jug 1'] = Jnew
  366.         if J1 < C1 and J0 > 0:
  367.             delta = min(J0, C1 - J1)
  368.             Jnew = J0 - delta, J1 + delta
  369.             successors['pour jug 0 into jug 1'] = Jnew
  370.         if J0 < C0 and J1 > 0:
  371.             delta = min(J1, C0 - J0)
  372.             Jnew = J0 + delta, J1 - delta
  373.             successors['pour jug 1 into jug 0'] = Jnew
  374.         return successors
  375.  
  376.     def actions(self, state):
  377.         return self.successor(state).keys()
  378.  
  379.     def result(self, state, action):
  380.         possible = self.successor(state)
  381.         return possible[action]
  382.  
  383.  
  384. # So vaka definiraniot problem mozeme da gi koristime site neinformirani prebaruvanja
  385. # Vo prodolzenie se dadeni mozni povici (vnimavajte za da moze da napravite povik mora da definirate problem)
  386. #
  387. #    WJInstance = WJ((5, 2), (5, 2), ('*', 1))
  388. #    print WJInstance
  389. #
  390. #    answer1 = breadth_first_tree_search(WJInstance)
  391. #    print answer1.solve()
  392. #
  393. #    answer2 = depth_first_tree_search(WJInstance) #vnimavajte na ovoj povik, moze da vleze vo beskonecna jamka
  394. #    print answer2.solve()
  395. #
  396. #    answer3 = breadth_first_graph_search(WJInstance)
  397. #    print answer3.solve()
  398. #
  399. #    answer4 = depth_first_graph_search(WJInstance)
  400. #    print answer4.solve()
  401. #
  402. #    answer5 = depth_limited_search(WJInstance)
  403. #    print answer5.solve()
  404. #
  405. #    answer6 = iterative_deepening_search(WJInstance)
  406. #    print answer6.solve()
  407. class CrnoBelo(Problem):
  408.     def __init__(self, initial, goal):
  409.         self.initial = str(initial)
  410.         self.goal = str(goal)
  411.  
  412.     def goal_test(self, state):
  413.         return state == self.goal
  414.  
  415.     def successor(self, state):
  416.         successors = dict()
  417.         dx = [-1, 0, 1, 0]
  418.         dy = [0, 1, 0, -1]
  419.         for x in range(0, N):
  420.             for y in range(0, N):
  421.                 Matrix = eval(state)
  422.                 if Matrix[x][y] == 1:
  423.                     Matrix[x][y] = 0
  424.                     for k in range(4):
  425.                         newX = x + dx[k]
  426.                         newY = y + dy[k]
  427.                         if newX >= 0 and newX < N and newY >= 0 and newY < N:
  428.                             Matrix[newX][newY] = (Matrix[newX][newY] + 1) % 2
  429.                     stateNew = Matrix
  430.                     akcija = "X:" + str(x) + "Y:" + str(y)
  431.                     successors[akcija] = str(stateNew)
  432.  
  433.         return successors
  434.  
  435.     def actions(self, state):
  436.         return self.successor(state).keys()
  437.  
  438.     def result(self, state, action):
  439.         possible = self.successor(state)
  440.         return possible[action]
  441.  
  442.  
  443. N = int(input())
  444. polinja = map(int, input().split(','))
  445. polinjaList = list(polinja)
  446. InitialMatrix = [[0 for x in range(N)] for y in range(N)]
  447. for i in range(0, N):
  448.     for j in range(0, N):
  449.         InitialMatrix[i][j] = polinjaList[i * N + j]
  450. GoalMatrix = [[0 for x in range(N)] for y in range(N)]
  451.  
  452. crnoBeloinstance = CrnoBelo(InitialMatrix, GoalMatrix)
  453. answer = breadth_first_graph_search(crnoBeloinstance).solution()
  454. print(answer)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top