Advertisement
cimona

PodvizniPrepreki

Sep 14th, 2018
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.77 KB | None | 0 0
  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. infinity = float('inf') # sistemski definirana vrednost za beskonecnost
  10.  
  11.  
  12. # ______________________________________________________________________________________________
  13. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  14.  
  15. class Queue:
  16. """Queue is an abstract class/interface. There are three types:
  17. Stack(): A Last In First Out Queue.
  18. FIFOQueue(): A First In First Out Queue.
  19. PriorityQueue(order, f): Queue in sorted order (default min-first).
  20. Each type supports the following methods and functions:
  21. q.append(item) -- add an item to the queue
  22. q.extend(items) -- equivalent to: for item in items: q.append(item)
  23. q.pop() -- return the top item from the queue
  24. len(q) -- number of items in q (also q.__len())
  25. item in q -- does q contain item?
  26. Note that isinstance(Stack(), Queue) is false, because we implement stacks
  27. as lists. If Python ever gets interfaces, Queue will be an interface."""
  28.  
  29. def __init__(self):
  30. raise NotImplementedError
  31.  
  32. def extend(self, items):
  33. for item in items:
  34. self.append(item)
  35.  
  36.  
  37. def Stack():
  38. """A Last-In-First-Out Queue."""
  39. return []
  40.  
  41.  
  42. class FIFOQueue(Queue):
  43. """A First-In-First-Out Queue."""
  44.  
  45. def __init__(self):
  46. self.A = []
  47. self.start = 0
  48.  
  49. def append(self, item):
  50. self.A.append(item)
  51.  
  52. def __len__(self):
  53. return len(self.A) - self.start
  54.  
  55. def extend(self, items):
  56. self.A.extend(items)
  57.  
  58. def pop(self):
  59. e = self.A[self.start]
  60. self.start += 1
  61. if self.start > 5 and self.start > len(self.A) / 2:
  62. self.A = self.A[self.start:]
  63. self.start = 0
  64. return e
  65.  
  66. def __contains__(self, item):
  67. return item in self.A[self.start:]
  68.  
  69.  
  70. class PriorityQueue(Queue):
  71. """A queue in which the minimum (or maximum) element (as determined by f and
  72. order) is returned first. If order is min, the item with minimum f(x) is
  73. returned first; if order is max, then it is the item with maximum f(x).
  74. Also supports dict-like lookup. This structure will be most useful in informed searches"""
  75.  
  76. def __init__(self, order=min, f=lambda x: x):
  77. self.A = []
  78. self.order = order
  79. self.f = f
  80.  
  81. def append(self, item):
  82. bisect.insort(self.A, (self.f(item), item))
  83.  
  84. def __len__(self):
  85. return len(self.A)
  86.  
  87. def pop(self):
  88. if self.order == min:
  89. return self.A.pop(0)[1]
  90. else:
  91. return self.A.pop()[1]
  92.  
  93. def __contains__(self, item):
  94. return any(item == pair[1] for pair in self.A)
  95.  
  96. def __getitem__(self, key):
  97. for _, item in self.A:
  98. if item == key:
  99. return item
  100.  
  101. def __delitem__(self, key):
  102. for i, (value, item) in enumerate(self.A):
  103. if item == key:
  104. self.A.pop(i)
  105.  
  106.  
  107. # ______________________________________________________________________________________________
  108. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  109. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  110. # na sekoj eden problem sto sakame da go resime
  111.  
  112.  
  113. class Problem:
  114. """The abstract class for a formal problem. You should subclass this and
  115. implement the method successor, and possibly __init__, goal_test, and
  116. path_cost. Then you will create instances of your subclass and solve them
  117. with the various search functions."""
  118.  
  119. def __init__(self, initial, goal=None):
  120. """The constructor specifies the initial state, and possibly a goal
  121. state, if there is a unique goal. Your subclass's constructor can add
  122. other arguments."""
  123. self.initial = initial
  124. self.goal = goal
  125.  
  126. def successor(self, state):
  127. """Given a state, return a dictionary of {action : state} pairs reachable
  128. from this state. If there are many successors, consider an iterator
  129. that yields the successors one at a time, rather than building them
  130. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  131. raise NotImplementedError
  132.  
  133. def actions(self, state):
  134. """Given a state, return a list of all actions possible from that state"""
  135. raise NotImplementedError
  136.  
  137. def result(self, state, action):
  138. """Given a state and action, return the resulting state"""
  139. raise NotImplementedError
  140.  
  141. def goal_test(self, state):
  142. """Return True if the state is a goal. The default method compares the
  143. state to self.goal, as specified in the constructor. Implement this
  144. method if checking against a single self.goal is not enough."""
  145. return state == self.goal
  146.  
  147. def path_cost(self, c, state1, action, state2):
  148. """Return the cost of a solution path that arrives at state2 from
  149. state1 via action, assuming cost c to get up to state1. If the problem
  150. is such that the path doesn't matter, this function will only look at
  151. state2. If the path does matter, it will consider c and maybe state1
  152. and action. The default method costs 1 for every step in the path."""
  153. return c + 1
  154.  
  155. def value(self):
  156. """For optimization problems, each state has a value. Hill-climbing
  157. and related algorithms try to maximize this value."""
  158. raise NotImplementedError
  159.  
  160.  
  161. # ______________________________________________________________________________
  162. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  163. # Klasata Node ne se nasleduva
  164.  
  165. class Node:
  166. """A node in a search tree. Contains a pointer to the parent (the node
  167. that this is a successor of) and to the actual state for this node. Note
  168. that if a state is arrived at by two paths, then there are two nodes with
  169. the same state. Also includes the action that got us to this state, and
  170. the total path_cost (also known as g) to reach the node. Other functions
  171. may add an f and h value; see best_first_graph_search and astar_search for
  172. an explanation of how the f and h values are handled. You will not need to
  173. subclass this class."""
  174.  
  175. def __init__(self, state, parent=None, action=None, path_cost=0):
  176. "Create a search tree Node, derived from a parent by an action."
  177. self.state = state
  178. self.parent = parent
  179. self.action = action
  180. self.path_cost = path_cost
  181. self.depth = 0
  182. if parent:
  183. self.depth = parent.depth + 1
  184.  
  185. def __repr__(self):
  186. return "<Node %s>" % (self.state,)
  187.  
  188. def __lt__(self, node):
  189. return self.state < node.state
  190.  
  191. def expand(self, problem):
  192. "List the nodes reachable in one step from this node."
  193. return [self.child_node(problem, action)
  194. for action in problem.actions(self.state)]
  195.  
  196. def child_node(self, problem, action):
  197. "Return a child node from this node"
  198. next = problem.result(self.state, action)
  199. return Node(next, self, action,
  200. problem.path_cost(self.path_cost, self.state,
  201. action, next))
  202.  
  203. def solution(self):
  204. "Return the sequence of actions to go from the root to this node."
  205. return [node.action for node in self.path()[1:]]
  206.  
  207. def solve(self):
  208. "Return the sequence of states to go from the root to this node."
  209. return [node.state for node in self.path()[0:]]
  210.  
  211. def path(self):
  212. "Return a list of nodes forming the path from the root to this node."
  213. x, result = self, []
  214. while x:
  215. result.append(x)
  216. x = x.parent
  217. return list(reversed(result))
  218.  
  219. # We want for a queue of nodes in breadth_first_search or
  220. # astar_search to have no duplicated states, so we treat nodes
  221. # with the same state as equal. [Problem: this may not be what you
  222. # want in other contexts.]
  223.  
  224. def __eq__(self, other):
  225. return isinstance(other, Node) and self.state == other.state
  226.  
  227. def __hash__(self):
  228. return hash(self.state)
  229.  
  230.  
  231. # ________________________________________________________________________________________________________
  232. #Neinformirano prebaruvanje vo ramki na drvo
  233. #Vo ramki na drvoto ne razresuvame jamki
  234.  
  235. def tree_search(problem, fringe):
  236. """Search through the successors of a problem to find a goal.
  237. The argument fringe should be an empty queue."""
  238. fringe.append(Node(problem.initial))
  239. while fringe:
  240. node = fringe.pop()
  241. print node.state
  242. if problem.goal_test(node.state):
  243. return node
  244. fringe.extend(node.expand(problem))
  245. return None
  246.  
  247.  
  248. def breadth_first_tree_search(problem):
  249. "Search the shallowest nodes in the search tree first."
  250. return tree_search(problem, FIFOQueue())
  251.  
  252.  
  253. def depth_first_tree_search(problem):
  254. "Search the deepest nodes in the search tree first."
  255. return tree_search(problem, Stack())
  256.  
  257.  
  258. # ________________________________________________________________________________________________________
  259. #Neinformirano prebaruvanje vo ramki na graf
  260. #Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  261.  
  262. def graph_search(problem, fringe):
  263. """Search through the successors of a problem to find a goal.
  264. The argument fringe should be an empty queue.
  265. If two paths reach a state, only use the best one."""
  266. closed = {}
  267. fringe.append(Node(problem.initial))
  268. while fringe:
  269. node = fringe.pop()
  270. if problem.goal_test(node.state):
  271. return node
  272. if node.state not in closed:
  273. closed[node.state] = True
  274. fringe.extend(node.expand(problem))
  275. return None
  276.  
  277.  
  278. def breadth_first_graph_search(problem):
  279. "Search the shallowest nodes in the search tree first."
  280. return graph_search(problem, FIFOQueue())
  281.  
  282.  
  283. def depth_first_graph_search(problem):
  284. "Search the deepest nodes in the search tree first."
  285. return graph_search(problem, Stack())
  286.  
  287.  
  288. def uniform_cost_search(problem):
  289. "Search the nodes in the search tree with lowest cost first."
  290. return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  291.  
  292.  
  293. def depth_limited_search(problem, limit=50):
  294. "depth first search with limited depth"
  295.  
  296. def recursive_dls(node, problem, limit):
  297. "helper function for depth limited"
  298. cutoff_occurred = False
  299. if problem.goal_test(node.state):
  300. return node
  301. elif node.depth == limit:
  302. return 'cutoff'
  303. else:
  304. for successor in node.expand(problem):
  305. result = recursive_dls(successor, problem, limit)
  306. if result == 'cutoff':
  307. cutoff_occurred = True
  308. elif result != None:
  309. return result
  310. if cutoff_occurred:
  311. return 'cutoff'
  312. else:
  313. return None
  314.  
  315. # Body of depth_limited_search:
  316. return recursive_dls(Node(problem.initial), problem, limit)
  317.  
  318.  
  319. def iterative_deepening_search(problem):
  320.  
  321. for depth in xrange(sys.maxint):
  322. result = depth_limited_search(problem, depth)
  323. if result is not 'cutoff':
  324. return result
  325.  
  326.  
  327.  
  328. # _________________________________________________________________________________________________________
  329. #Vasiot kod pisuvajte go pod ovoj komentar
  330.  
  331. # Python modul vo koj se implementirani algoritmite za neinformirano i informirano prebaruvanje
  332.  
  333. # ______________________________________________________________________________________________
  334. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  335.  
  336. import sys
  337. import bisect
  338.  
  339. infinity = float('inf') # sistemski definirana vrednost za beskonecnost
  340.  
  341.  
  342. # ______________________________________________________________________________________________
  343. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  344.  
  345. class Queue:
  346. """Queue is an abstract class/interface. There are three types:
  347. Stack(): A Last In First Out Queue.
  348. FIFOQueue(): A First In First Out Queue.
  349. PriorityQueue(order, f): Queue in sorted order (default min-first).
  350. Each type supports the following methods and functions:
  351. q.append(item) -- add an item to the queue
  352. q.extend(items) -- equivalent to: for item in items: q.append(item)
  353. q.pop() -- return the top item from the queue
  354. len(q) -- number of items in q (also q.__len())
  355. item in q -- does q contain item?
  356. Note that isinstance(Stack(), Queue) is false, because we implement stacks
  357. as lists. If Python ever gets interfaces, Queue will be an interface."""
  358.  
  359. def __init__(self):
  360. raise NotImplementedError
  361.  
  362. def extend(self, items):
  363. for item in items:
  364. self.append(item)
  365.  
  366.  
  367. def Stack():
  368. """A Last-In-First-Out Queue."""
  369. return []
  370.  
  371.  
  372. class FIFOQueue(Queue):
  373. """A First-In-First-Out Queue."""
  374.  
  375. def __init__(self):
  376. self.A = []
  377. self.start = 0
  378.  
  379. def append(self, item):
  380. self.A.append(item)
  381.  
  382. def __len__(self):
  383. return len(self.A) - self.start
  384.  
  385. def extend(self, items):
  386. self.A.extend(items)
  387.  
  388. def pop(self):
  389. e = self.A[self.start]
  390. self.start += 1
  391. if self.start > 5 and self.start > len(self.A) / 2:
  392. self.A = self.A[self.start:]
  393. self.start = 0
  394. return e
  395.  
  396. def __contains__(self, item):
  397. return item in self.A[self.start:]
  398.  
  399.  
  400. class PriorityQueue(Queue):
  401. """A queue in which the minimum (or maximum) element (as determined by f and
  402. order) is returned first. If order is min, the item with minimum f(x) is
  403. returned first; if order is max, then it is the item with maximum f(x).
  404. Also supports dict-like lookup. This structure will be most useful in informed searches"""
  405.  
  406. def __init__(self, order=min, f=lambda x: x):
  407. self.A = []
  408. self.order = order
  409. self.f = f
  410.  
  411. def append(self, item):
  412. bisect.insort(self.A, (self.f(item), item))
  413.  
  414. def __len__(self):
  415. return len(self.A)
  416.  
  417. def pop(self):
  418. if self.order == min:
  419. return self.A.pop(0)[1]
  420. else:
  421. return self.A.pop()[1]
  422.  
  423. def __contains__(self, item):
  424. return any(item == pair[1] for pair in self.A)
  425.  
  426. def __getitem__(self, key):
  427. for _, item in self.A:
  428. if item == key:
  429. return item
  430.  
  431. def __delitem__(self, key):
  432. for i, (value, item) in enumerate(self.A):
  433. if item == key:
  434. self.A.pop(i)
  435.  
  436.  
  437. # ______________________________________________________________________________________________
  438. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  439. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  440. # na sekoj eden problem sto sakame da go resime
  441.  
  442.  
  443. class Problem:
  444. """The abstract class for a formal problem. You should subclass this and
  445. implement the method successor, and possibly __init__, goal_test, and
  446. path_cost. Then you will create instances of your subclass and solve them
  447. with the various search functions."""
  448.  
  449. def __init__(self, initial, goal=None):
  450. """The constructor specifies the initial state, and possibly a goal
  451. state, if there is a unique goal. Your subclass's constructor can add
  452. other arguments."""
  453. self.initial = initial
  454. self.goal = goal
  455.  
  456. def successor(self, state):
  457. """Given a state, return a dictionary of {action : state} pairs reachable
  458. from this state. If there are many successors, consider an iterator
  459. that yields the successors one at a time, rather than building them
  460. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  461. raise NotImplementedError
  462.  
  463. def actions(self, state):
  464. """Given a state, return a list of all actions possible from that state"""
  465. raise NotImplementedError
  466.  
  467. def result(self, state, action):
  468. """Given a state and action, return the resulting state"""
  469. raise NotImplementedError
  470.  
  471. def goal_test(self, state):
  472. """Return True if the state is a goal. The default method compares the
  473. state to self.goal, as specified in the constructor. Implement this
  474. method if checking against a single self.goal is not enough."""
  475. return state == self.goal
  476.  
  477. def path_cost(self, c, state1, action, state2):
  478. """Return the cost of a solution path that arrives at state2 from
  479. state1 via action, assuming cost c to get up to state1. If the problem
  480. is such that the path doesn't matter, this function will only look at
  481. state2. If the path does matter, it will consider c and maybe state1
  482. and action. The default method costs 1 for every step in the path."""
  483. return c + 1
  484.  
  485. def value(self):
  486. """For optimization problems, each state has a value. Hill-climbing
  487. and related algorithms try to maximize this value."""
  488. raise NotImplementedError
  489.  
  490.  
  491. # ______________________________________________________________________________
  492. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  493. # Klasata Node ne se nasleduva
  494.  
  495. class Node:
  496. """A node in a search tree. Contains a pointer to the parent (the node
  497. that this is a successor of) and to the actual state for this node. Note
  498. that if a state is arrived at by two paths, then there are two nodes with
  499. the same state. Also includes the action that got us to this state, and
  500. the total path_cost (also known as g) to reach the node. Other functions
  501. may add an f and h value; see best_first_graph_search and astar_search for
  502. an explanation of how the f and h values are handled. You will not need to
  503. subclass this class."""
  504.  
  505. def __init__(self, state, parent=None, action=None, path_cost=0):
  506. "Create a search tree Node, derived from a parent by an action."
  507. self.state = state
  508. self.parent = parent
  509. self.action = action
  510. self.path_cost = path_cost
  511. self.depth = 0
  512. if parent:
  513. self.depth = parent.depth + 1
  514.  
  515. def __repr__(self):
  516. return "<Node %s>" % (self.state,)
  517.  
  518. def __lt__(self, node):
  519. return self.state < node.state
  520.  
  521. def expand(self, problem):
  522. "List the nodes reachable in one step from this node."
  523. return [self.child_node(problem, action)
  524. for action in problem.actions(self.state)]
  525.  
  526. def child_node(self, problem, action):
  527. "Return a child node from this node"
  528. next = problem.result(self.state, action)
  529. return Node(next, self, action,
  530. problem.path_cost(self.path_cost, self.state,
  531. action, next))
  532.  
  533. def solution(self):
  534. "Return the sequence of actions to go from the root to this node."
  535. return [node.action for node in self.path()[1:]]
  536.  
  537. def solve(self):
  538. "Return the sequence of states to go from the root to this node."
  539. return [node.state for node in self.path()[0:]]
  540.  
  541. def path(self):
  542. "Return a list of nodes forming the path from the root to this node."
  543. x, result = self, []
  544. while x:
  545. result.append(x)
  546. x = x.parent
  547. return list(reversed(result))
  548.  
  549. # We want for a queue of nodes in breadth_first_search or
  550. # astar_search to have no duplicated states, so we treat nodes
  551. # with the same state as equal. [Problem: this may not be what you
  552. # want in other contexts.]
  553.  
  554. def __eq__(self, other):
  555. return isinstance(other, Node) and self.state == other.state
  556.  
  557. def __hash__(self):
  558. return hash(self.state)
  559.  
  560.  
  561. # ________________________________________________________________________________________________________
  562. #Neinformirano prebaruvanje vo ramki na drvo
  563. #Vo ramki na drvoto ne razresuvame jamki
  564.  
  565. def tree_search(problem, fringe):
  566. """Search through the successors of a problem to find a goal.
  567. The argument fringe should be an empty queue."""
  568. fringe.append(Node(problem.initial))
  569. while fringe:
  570. node = fringe.pop()
  571. print node.state
  572. if problem.goal_test(node.state):
  573. return node
  574. fringe.extend(node.expand(problem))
  575. return None
  576.  
  577.  
  578. def breadth_first_tree_search(problem):
  579. "Search the shallowest nodes in the search tree first."
  580. return tree_search(problem, FIFOQueue())
  581.  
  582.  
  583. def depth_first_tree_search(problem):
  584. "Search the deepest nodes in the search tree first."
  585. return tree_search(problem, Stack())
  586.  
  587.  
  588. # ________________________________________________________________________________________________________
  589. #Neinformirano prebaruvanje vo ramki na graf
  590. #Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  591.  
  592. def graph_search(problem, fringe):
  593. """Search through the successors of a problem to find a goal.
  594. The argument fringe should be an empty queue.
  595. If two paths reach a state, only use the best one."""
  596. closed = {}
  597. fringe.append(Node(problem.initial))
  598. while fringe:
  599. node = fringe.pop()
  600. if problem.goal_test(node.state):
  601. return node
  602. if node.state not in closed:
  603. closed[node.state] = True
  604. fringe.extend(node.expand(problem))
  605. return None
  606.  
  607.  
  608. def breadth_first_graph_search(problem):
  609. "Search the shallowest nodes in the search tree first."
  610. return graph_search(problem, FIFOQueue())
  611.  
  612.  
  613. def depth_first_graph_search(problem):
  614. "Search the deepest nodes in the search tree first."
  615. return graph_search(problem, Stack())
  616.  
  617.  
  618. def uniform_cost_search(problem):
  619. "Search the nodes in the search tree with lowest cost first."
  620. return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  621.  
  622.  
  623. def depth_limited_search(problem, limit=50):
  624. "depth first search with limited depth"
  625.  
  626. def recursive_dls(node, problem, limit):
  627. "helper function for depth limited"
  628. cutoff_occurred = False
  629. if problem.goal_test(node.state):
  630. return node
  631. elif node.depth == limit:
  632. return 'cutoff'
  633. else:
  634. for successor in node.expand(problem):
  635. result = recursive_dls(successor, problem, limit)
  636. if result == 'cutoff':
  637. cutoff_occurred = True
  638. elif result != None:
  639. return result
  640. if cutoff_occurred:
  641. return 'cutoff'
  642. else:
  643. return None
  644.  
  645. # Body of depth_limited_search:
  646. return recursive_dls(Node(problem.initial), problem, limit)
  647.  
  648.  
  649. def iterative_deepening_search(problem):
  650.  
  651. for depth in xrange(sys.maxint):
  652. result = depth_limited_search(problem, depth)
  653. if result is not 'cutoff':
  654. return result
  655.  
  656.  
  657. # ________________________________________________________________________________________________________
  658. #Pomosna funkcija za informirani prebaruvanja
  659. #So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  660.  
  661. def memoize(fn, slot=None):
  662. """Memoize fn: make it remember the computed value for any argument list.
  663. If slot is specified, store result in that slot of first argument.
  664. If slot is false, store results in a dictionary."""
  665. if slot:
  666. def memoized_fn(obj, *args):
  667. if hasattr(obj, slot):
  668. return getattr(obj, slot)
  669. else:
  670. val = fn(obj, *args)
  671. setattr(obj, slot, val)
  672. return val
  673. else:
  674. def memoized_fn(*args):
  675. if not memoized_fn.cache.has_key(args):
  676. memoized_fn.cache[args] = fn(*args)
  677. return memoized_fn.cache[args]
  678.  
  679. memoized_fn.cache = {}
  680. return memoized_fn
  681.  
  682.  
  683. # ________________________________________________________________________________________________________
  684. #Informirano prebaruvanje vo ramki na graf
  685.  
  686. def best_first_graph_search(problem, f):
  687. """Search the nodes with the lowest f scores first.
  688. You specify the function f(node) that you want to minimize; for example,
  689. if f is a heuristic estimate to the goal, then we have greedy best
  690. first search; if f is node.depth then we have breadth-first search.
  691. There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  692. values will be cached on the nodes as they are computed. So after doing
  693. a best first search you can examine the f values of the path returned."""
  694.  
  695. f = memoize(f, 'f')
  696. node = Node(problem.initial)
  697. if problem.goal_test(node.state):
  698. return node
  699. frontier = PriorityQueue(min, f)
  700. frontier.append(node)
  701. explored = set()
  702. while frontier:
  703. node = frontier.pop()
  704. if problem.goal_test(node.state):
  705. return node
  706. explored.add(node.state)
  707. for child in node.expand(problem):
  708. if child.state not in explored and child not in frontier:
  709. frontier.append(child)
  710. elif child in frontier:
  711. incumbent = frontier[child]
  712. if f(child) < f(incumbent):
  713. del frontier[incumbent]
  714. frontier.append(child)
  715. return None
  716.  
  717.  
  718. def greedy_best_first_graph_search(problem, h=None):
  719. "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  720. h = memoize(h or problem.h, 'h')
  721. return best_first_graph_search(problem, h)
  722.  
  723.  
  724. def astar_search(problem, h=None):
  725. "A* search is best-first graph search with f(n) = g(n)+h(n)."
  726. h = memoize(h or problem.h, 'h')
  727. return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  728.  
  729.  
  730. # ________________________________________________________________________________________________________
  731. #Dopolnitelni prebaruvanja
  732. #Recursive_best_first_search e implementiran
  733. #Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  734.  
  735. def recursive_best_first_search(problem, h=None):
  736. h = memoize(h or problem.h, 'h')
  737.  
  738. def RBFS(problem, node, flimit):
  739. if problem.goal_test(node.state):
  740. return node, 0 # (The second value is immaterial)
  741. successors = node.expand(problem)
  742. if len(successors) == 0:
  743. return None, infinity
  744. for s in successors:
  745. s.f = max(s.path_cost + h(s), node.f)
  746. while True:
  747. # Order by lowest f value
  748. successors.sort(key=lambda x: x.f)
  749. best = successors[0]
  750. if best.f > flimit:
  751. return None, best.f
  752. if len(successors) > 1:
  753. alternative = successors[1].f
  754. else:
  755. alternative = infinity
  756. result, best.f = RBFS(problem, best, min(flimit, alternative))
  757. if result is not None:
  758. return result, best.f
  759.  
  760. node = Node(problem.initial)
  761. node.f = h(node)
  762. result, bestf = RBFS(problem, node, infinity)
  763. return result
  764.  
  765.  
  766. # Python modul vo koj se implementirani algoritmite za informirano prebaruvanje
  767.  
  768. # ______________________________________________________________________________________________
  769. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  770.  
  771. import sys
  772. import bisect
  773.  
  774. infinity = float('inf') # sistemski definirana vrednost za beskonecnost
  775.  
  776.  
  777. # ______________________________________________________________________________________________
  778. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  779.  
  780. class Queue:
  781. """Queue is an abstract class/interface. There are three types:
  782. Stack(): A Last In First Out Queue.
  783. FIFOQueue(): A First In First Out Queue.
  784. PriorityQueue(order, f): Queue in sorted order (default min-first).
  785. Each type supports the following methods and functions:
  786. q.append(item) -- add an item to the queue
  787. q.extend(items) -- equivalent to: for item in items: q.append(item)
  788. q.pop() -- return the top item from the queue
  789. len(q) -- number of items in q (also q.__len())
  790. item in q -- does q contain item?
  791. Note that isinstance(Stack(), Queue) is false, because we implement stacks
  792. as lists. If Python ever gets interfaces, Queue will be an interface."""
  793.  
  794. def __init__(self):
  795. raise NotImplementedError
  796.  
  797. def extend(self, items):
  798. for item in items:
  799. self.append(item)
  800.  
  801.  
  802. def Stack():
  803. """A Last-In-First-Out Queue."""
  804. return []
  805.  
  806.  
  807. class FIFOQueue(Queue):
  808. """A First-In-First-Out Queue."""
  809.  
  810. def __init__(self):
  811. self.A = []
  812. self.start = 0
  813.  
  814. def append(self, item):
  815. self.A.append(item)
  816.  
  817. def __len__(self):
  818. return len(self.A) - self.start
  819.  
  820. def extend(self, items):
  821. self.A.extend(items)
  822.  
  823. def pop(self):
  824. e = self.A[self.start]
  825. self.start += 1
  826. if self.start > 5 and self.start > len(self.A) / 2:
  827. self.A = self.A[self.start:]
  828. self.start = 0
  829. return e
  830.  
  831. def __contains__(self, item):
  832. return item in self.A[self.start:]
  833.  
  834.  
  835. class PriorityQueue(Queue):
  836. """A queue in which the minimum (or maximum) element (as determined by f and
  837. order) is returned first. If order is min, the item with minimum f(x) is
  838. returned first; if order is max, then it is the item with maximum f(x).
  839. Also supports dict-like lookup. This structure will be most useful in informed searches"""
  840.  
  841. def __init__(self, order=min, f=lambda x: x):
  842. self.A = []
  843. self.order = order
  844. self.f = f
  845.  
  846. def append(self, item):
  847. bisect.insort(self.A, (self.f(item), item))
  848.  
  849. def __len__(self):
  850. return len(self.A)
  851.  
  852. def pop(self):
  853. if self.order == min:
  854. return self.A.pop(0)[1]
  855. else:
  856. return self.A.pop()[1]
  857.  
  858. def __contains__(self, item):
  859. return any(item == pair[1] for pair in self.A)
  860.  
  861. def __getitem__(self, key):
  862. for _, item in self.A:
  863. if item == key:
  864. return item
  865.  
  866. def __delitem__(self, key):
  867. for i, (value, item) in enumerate(self.A):
  868. if item == key:
  869. self.A.pop(i)
  870.  
  871.  
  872. # ______________________________________________________________________________________________
  873. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  874. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  875. # na sekoj eden problem sto sakame da go resime
  876.  
  877.  
  878. class Problem:
  879. """The abstract class for a formal problem. You should subclass this and
  880. implement the method successor, and possibly __init__, goal_test, and
  881. path_cost. Then you will create instances of your subclass and solve them
  882. with the various search functions."""
  883.  
  884. def __init__(self, initial, goal=None):
  885. """The constructor specifies the initial state, and possibly a goal
  886. state, if there is a unique goal. Your subclass's constructor can add
  887. other arguments."""
  888. self.initial = initial
  889. self.goal = goal
  890.  
  891. def successor(self, state):
  892. """Given a state, return a dictionary of {action : state} pairs reachable
  893. from this state. If there are many successors, consider an iterator
  894. that yields the successors one at a time, rather than building them
  895. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  896. raise NotImplementedError
  897.  
  898. def actions(self, state):
  899. """Given a state, return a list of all actions possible from that state"""
  900. raise NotImplementedError
  901.  
  902. def result(self, state, action):
  903. """Given a state and action, return the resulting state"""
  904. raise NotImplementedError
  905.  
  906. def goal_test(self, state):
  907. """Return True if the state is a goal. The default method compares the
  908. state to self.goal, as specified in the constructor. Implement this
  909. method if checking against a single self.goal is not enough."""
  910. return state == self.goal
  911.  
  912. def path_cost(self, c, state1, action, state2):
  913. """Return the cost of a solution path that arrives at state2 from
  914. state1 via action, assuming cost c to get up to state1. If the problem
  915. is such that the path doesn't matter, this function will only look at
  916. state2. If the path does matter, it will consider c and maybe state1
  917. and action. The default method costs 1 for every step in the path."""
  918. return c + 1
  919.  
  920. def value(self):
  921. """For optimization problems, each state has a value. Hill-climbing
  922. and related algorithms try to maximize this value."""
  923. raise NotImplementedError
  924.  
  925.  
  926. # ______________________________________________________________________________
  927. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  928. # Klasata Node ne se nasleduva
  929.  
  930. class Node:
  931. """A node in a search tree. Contains a pointer to the parent (the node
  932. that this is a successor of) and to the actual state for this node. Note
  933. that if a state is arrived at by two paths, then there are two nodes with
  934. the same state. Also includes the action that got us to this state, and
  935. the total path_cost (also known as g) to reach the node. Other functions
  936. may add an f and h value; see best_first_graph_search and astar_search for
  937. an explanation of how the f and h values are handled. You will not need to
  938. subclass this class."""
  939.  
  940. def __init__(self, state, parent=None, action=None, path_cost=0):
  941. "Create a search tree Node, derived from a parent by an action."
  942. self.state = state
  943. self.parent = parent
  944. self.action = action
  945. self.path_cost = path_cost
  946. self.depth = 0
  947. if parent:
  948. self.depth = parent.depth + 1
  949.  
  950. def __repr__(self):
  951. return "<Node %s>" % (self.state,)
  952.  
  953. def __lt__(self, node):
  954. return self.state < node.state
  955.  
  956. def expand(self, problem):
  957. "List the nodes reachable in one step from this node."
  958. return [self.child_node(problem, action)
  959. for action in problem.actions(self.state)]
  960.  
  961. def child_node(self, problem, action):
  962. "Return a child node from this node"
  963. next = problem.result(self.state, action)
  964. return Node(next, self, action,
  965. problem.path_cost(self.path_cost, self.state,
  966. action, next))
  967.  
  968. def solution(self):
  969. "Return the sequence of actions to go from the root to this node."
  970. return [node.action for node in self.path()[1:]]
  971.  
  972. def solve(self):
  973. "Return the sequence of states to go from the root to this node."
  974. return [node.state for node in self.path()[0:]]
  975.  
  976. def path(self):
  977. "Return a list of nodes forming the path from the root to this node."
  978. x, result = self, []
  979. while x:
  980. result.append(x)
  981. x = x.parent
  982. return list(reversed(result))
  983.  
  984. # We want for a queue of nodes in breadth_first_search or
  985. # astar_search to have no duplicated states, so we treat nodes
  986. # with the same state as equal. [Problem: this may not be what you
  987. # want in other contexts.]
  988.  
  989. def __eq__(self, other):
  990. return isinstance(other, Node) and self.state == other.state
  991.  
  992. def __hash__(self):
  993. return hash(self.state)
  994.  
  995.  
  996.  
  997. # ________________________________________________________________________________________________________
  998. #Pomosna funkcija za informirani prebaruvanja
  999. #So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  1000.  
  1001. def memoize(fn, slot=None):
  1002. """Memoize fn: make it remember the computed value for any argument list.
  1003. If slot is specified, store result in that slot of first argument.
  1004. If slot is false, store results in a dictionary."""
  1005. if slot:
  1006. def memoized_fn(obj, *args):
  1007. if hasattr(obj, slot):
  1008. return getattr(obj, slot)
  1009. else:
  1010. val = fn(obj, *args)
  1011. setattr(obj, slot, val)
  1012. return val
  1013. else:
  1014. def memoized_fn(*args):
  1015. if not memoized_fn.cache.has_key(args):
  1016. memoized_fn.cache[args] = fn(*args)
  1017. return memoized_fn.cache[args]
  1018.  
  1019. memoized_fn.cache = {}
  1020. return memoized_fn
  1021.  
  1022.  
  1023. # ________________________________________________________________________________________________________
  1024. #Informirano prebaruvanje vo ramki na graf
  1025.  
  1026. def best_first_graph_search(problem, f):
  1027. """Search the nodes with the lowest f scores first.
  1028. You specify the function f(node) that you want to minimize; for example,
  1029. if f is a heuristic estimate to the goal, then we have greedy best
  1030. first search; if f is node.depth then we have breadth-first search.
  1031. There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  1032. values will be cached on the nodes as they are computed. So after doing
  1033. a best first search you can examine the f values of the path returned."""
  1034.  
  1035. f = memoize(f, 'f')
  1036. node = Node(problem.initial)
  1037. if problem.goal_test(node.state):
  1038. return node
  1039. frontier = PriorityQueue(min, f)
  1040. frontier.append(node)
  1041. explored = set()
  1042. while frontier:
  1043. node = frontier.pop()
  1044. if problem.goal_test(node.state):
  1045. return node
  1046. explored.add(node.state)
  1047. for child in node.expand(problem):
  1048. if child.state not in explored and child not in frontier:
  1049. frontier.append(child)
  1050. elif child in frontier:
  1051. incumbent = frontier[child]
  1052. if f(child) < f(incumbent):
  1053. del frontier[incumbent]
  1054. frontier.append(child)
  1055. return None
  1056.  
  1057.  
  1058. def greedy_best_first_graph_search(problem, h=None):
  1059. "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  1060. h = memoize(h or problem.h, 'h')
  1061. return best_first_graph_search(problem, h)
  1062.  
  1063.  
  1064. def astar_search(problem, h=None):
  1065. "A* search is best-first graph search with f(n) = g(n)+h(n)."
  1066. h = memoize(h or problem.h, 'h')
  1067. return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  1068.  
  1069.  
  1070. # ________________________________________________________________________________________________________
  1071. #Dopolnitelni prebaruvanja
  1072. #Recursive_best_first_search e implementiran
  1073. #Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  1074.  
  1075. def recursive_best_first_search(problem, h=None):
  1076. h = memoize(h or problem.h, 'h')
  1077.  
  1078. def RBFS(problem, node, flimit):
  1079. if problem.goal_test(node.state):
  1080. return node, 0 # (The second value is immaterial)
  1081. successors = node.expand(problem)
  1082. if len(successors) == 0:
  1083. return None, infinity
  1084. for s in successors:
  1085. s.f = max(s.path_cost + h(s), node.f)
  1086. while True:
  1087. # Order by lowest f value
  1088. successors.sort(key=lambda x: x.f)
  1089. best = successors[0]
  1090. if best.f > flimit:
  1091. return None, best.f
  1092. if len(successors) > 1:
  1093. alternative = successors[1].f
  1094. else:
  1095. alternative = infinity
  1096. result, best.f = RBFS(problem, best, min(flimit, alternative))
  1097. if result is not None:
  1098. return result, best.f
  1099.  
  1100. node = Node(problem.initial)
  1101. node.f = h(node)
  1102. result, bestf = RBFS(problem, node, infinity)
  1103. return result
  1104.  
  1105.  
  1106.  
  1107. # _________________________________________________________________________________________________________
  1108. #Vcituvanje na vleznite argumenti za test primerite
  1109.  
  1110. def precka1(P):
  1111. x=P[0]
  1112. y=P[1]
  1113. n=P[2]
  1114.  
  1115. if x==2 and y==0 and n==-1:
  1116. x=x
  1117. y=y+1
  1118. n=n*(-1)
  1119. elif x==2 and y==4 and n==+1:
  1120. x=x
  1121. y=y-1
  1122. n=n*(-1)
  1123. else:
  1124. x=x
  1125. y=y+n
  1126. n=n
  1127.  
  1128. Pnew=x,y,n
  1129. return Pnew
  1130.  
  1131. def precka2(P):
  1132. x=P[0]
  1133. y=P[1]
  1134. n=P[2]
  1135. if x==9 and y==1 and n==-1:
  1136. x=x-1
  1137. y=y+1
  1138. n=n*(-1)
  1139. elif x==5 and y==5 and n==+1:
  1140. x=x+1
  1141. y=y-1
  1142. n=n*(-1)
  1143. else:
  1144. x=x-n
  1145. y=y+n
  1146. n=n
  1147.  
  1148. Pnew=x,y,n
  1149. return Pnew
  1150.  
  1151. def precka3(P):
  1152. x=P[0]
  1153. y=P[1]
  1154. n=P[2]
  1155.  
  1156. if x==6 and y==8 and n==-1:
  1157. x=x+1
  1158. y=y
  1159. n=n*(-1)
  1160. elif x==10 and y==8 and n==+1:
  1161. x=x-1
  1162. y=y
  1163. n=n*(-1)
  1164. else:
  1165. x=x+n
  1166. y=y
  1167. n=n
  1168.  
  1169. Pnew=x,y,n
  1170. return Pnew
  1171.  
  1172. def validno(V):
  1173. Cx=V[0]
  1174. Cy=V[1]
  1175. p1x=V[2]
  1176. p1y=V[3]
  1177. p2x=V[4]
  1178. p2y=V[5]
  1179. p3x=V[6]
  1180. p3y=V[7]
  1181.  
  1182. t=False
  1183. if (Cx != p1x or Cy != p1y) and (Cx != p1x or Cy != p1y+1) and (Cx != p2x or Cy != p2y) and (Cx != p2x or Cy != p2y-1) and (Cx != p2x+1 or Cy != p2y-1) and (Cx != p2x+1 or Cy != p2y) and (Cx != p3x or Cy != p3y) and (Cx != p3x+1 or Cy != p3y):
  1184. t=True
  1185. else:
  1186. t=False
  1187. return t
  1188.  
  1189.  
  1190. class PP(Problem):
  1191.  
  1192. def __init__(self, initial, goal):
  1193. self.initial = initial
  1194. self.goal = goal
  1195.  
  1196. def successor(self, state):
  1197. succs = dict()
  1198.  
  1199. x=state[0]
  1200. y=state[1]
  1201. p1=(state[2],state[3],state[4])
  1202. p2=(state[5],state[6],state[7])
  1203. p3=(state[8],state[9],state[10])
  1204.  
  1205. if (y<5 and y>=0 and x >=0 and x<5) or (y<10 and y>=0 and x>4 and x<11):
  1206. Xnew=x
  1207. Ynew=y+1
  1208. p1New=precka1(p1)
  1209. p2New=precka2(p2)
  1210. p3New=precka3(p3)
  1211. V=(Xnew,Ynew,p1New[0],p1New[1],p2New[0],p2New[1],p3New[0],p3New[1])
  1212. v=validno(V)
  1213. if(v==True):
  1214. StateNew=(Xnew,Ynew,p1New[0],p1New[1],p1New[2],p2New[0],p2New[1],p2New[2],p3New[0],p3New[1],p3New[2])
  1215. succs['Desno']=StateNew
  1216.  
  1217. if (y>0 and y<6 and x>=0 and x<5) or (y>0 and y<11 and x>4 and x<11):
  1218. Xnew=x
  1219. Ynew=y-1
  1220. p1New=precka1(p1)
  1221. p2New=precka2(p2)
  1222. p3New=precka3(p3)
  1223. V=(Xnew,Ynew,p1New[0],p1New[1],p2New[0],p2New[1],p3New[0],p3New[1])
  1224. v=validno(V)
  1225. if(v==True):
  1226. StateNew=(Xnew,Ynew,p1New[0],p1New[1],p1New[2],p2New[0],p2New[1],p2New[2],p3New[0],p3New[1],p3New[2])
  1227. succs['Levo']=StateNew
  1228.  
  1229.  
  1230. if (x>0 and x<11 and y>=0 and y<6) or (x>5 and x<11 and y>5 and y<11):
  1231. Xnew=x-1
  1232. Ynew=y
  1233. p1New=precka1(p1)
  1234. p2New=precka2(p2)
  1235. p3New=precka3(p3)
  1236. V=(Xnew,Ynew,p1New[0],p1New[1],p2New[0],p2New[1],p3New[0],p3New[1])
  1237. v=validno(V)
  1238. if(v==True):
  1239. StateNew=(Xnew,Ynew,p1New[0],p1New[1],p1New[2],p2New[0],p2New[1],p2New[2],p3New[0],p3New[1],p3New[2])
  1240. succs['Gore']=StateNew
  1241.  
  1242. if (x<10 and x>=0 and y>=0 and y<6) or (x<10 and x>4 and y>5 and y<11):
  1243. Xnew=x+1
  1244. Ynew=y
  1245. p1New=precka1(p1)
  1246. p2New=precka2(p2)
  1247. p3New=precka3(p3)
  1248. V=(Xnew,Ynew,p1New[0],p1New[1],p2New[0],p2New[1],p3New[0],p3New[1])
  1249. v=validno(V)
  1250. if(v==True):
  1251. StateNew=(Xnew,Ynew,p1New[0],p1New[1],p1New[2],p2New[0],p2New[1],p2New[2],p3New[0],p3New[1],p3New[2])
  1252. succs['Dolu']=StateNew
  1253.  
  1254. return succs
  1255.  
  1256.  
  1257. def actions(self, state):
  1258. return self.successor(state).keys()
  1259.  
  1260. def result(self, state, action):
  1261. possible = self.successor(state)
  1262. return possible[action]
  1263.  
  1264. def goal_test(self, state):
  1265. G = self.goal
  1266. return (state[0] == G[0] and state[1] == G[1])
  1267.  
  1268.  
  1269.  
  1270. CoveceRedica = int(input())
  1271. CoveceKolona = int(input())
  1272. KukaRedica = int(input())
  1273. KukaKolona = int(input())
  1274.  
  1275. K = [KukaRedica,KukaKolona]
  1276. PPinstanca = PP((CoveceRedica, CoveceKolona, 2, 2, -1, 7, 3, +1, 8, 8, +1), K)
  1277. answer = breadth_first_graph_search(PPinstanca)
  1278. print answer.solution()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement