cimona

PodvizniPreprekiInformirano

Sep 14th, 2018
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.09 KB | None | 0 0
  1. #Vasiot kod pisuvajte go pod ovoj komentar
  2.  
  3. # Python modul vo koj se implementirani algoritmite za neinformirano i informirano prebaruvanje
  4.  
  5. # ______________________________________________________________________________________________
  6. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  7.  
  8. import sys
  9. import bisect
  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.  
  323. for depth in xrange(sys.maxint):
  324. result = depth_limited_search(problem, depth)
  325. if result is not 'cutoff':
  326. return result
  327.  
  328.  
  329. # ________________________________________________________________________________________________________
  330. #Pomosna funkcija za informirani prebaruvanja
  331. #So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  332.  
  333. def memoize(fn, slot=None):
  334. """Memoize fn: make it remember the computed value for any argument list.
  335. If slot is specified, store result in that slot of first argument.
  336. If slot is false, store results in a dictionary."""
  337. if slot:
  338. def memoized_fn(obj, *args):
  339. if hasattr(obj, slot):
  340. return getattr(obj, slot)
  341. else:
  342. val = fn(obj, *args)
  343. setattr(obj, slot, val)
  344. return val
  345. else:
  346. def memoized_fn(*args):
  347. if not memoized_fn.cache.has_key(args):
  348. memoized_fn.cache[args] = fn(*args)
  349. return memoized_fn.cache[args]
  350.  
  351. memoized_fn.cache = {}
  352. return memoized_fn
  353.  
  354.  
  355. # ________________________________________________________________________________________________________
  356. #Informirano prebaruvanje vo ramki na graf
  357.  
  358. def best_first_graph_search(problem, f):
  359. """Search the nodes with the lowest f scores first.
  360. You specify the function f(node) that you want to minimize; for example,
  361. if f is a heuristic estimate to the goal, then we have greedy best
  362. first search; if f is node.depth then we have breadth-first search.
  363. There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  364. values will be cached on the nodes as they are computed. So after doing
  365. a best first search you can examine the f values of the path returned."""
  366.  
  367. f = memoize(f, 'f')
  368. node = Node(problem.initial)
  369. if problem.goal_test(node.state):
  370. return node
  371. frontier = PriorityQueue(min, f)
  372. frontier.append(node)
  373. explored = set()
  374. while frontier:
  375. node = frontier.pop()
  376. if problem.goal_test(node.state):
  377. return node
  378. explored.add(node.state)
  379. for child in node.expand(problem):
  380. if child.state not in explored and child not in frontier:
  381. frontier.append(child)
  382. elif child in frontier:
  383. incumbent = frontier[child]
  384. if f(child) < f(incumbent):
  385. del frontier[incumbent]
  386. frontier.append(child)
  387. return None
  388.  
  389.  
  390. def greedy_best_first_graph_search(problem, h=None):
  391. "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  392. h = memoize(h or problem.h, 'h')
  393. return best_first_graph_search(problem, h)
  394.  
  395.  
  396. def astar_search(problem, h=None):
  397. "A* search is best-first graph search with f(n) = g(n)+h(n)."
  398. h = memoize(h or problem.h, 'h')
  399. return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  400.  
  401.  
  402. # ________________________________________________________________________________________________________
  403. #Dopolnitelni prebaruvanja
  404. #Recursive_best_first_search e implementiran
  405. #Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  406.  
  407. def recursive_best_first_search(problem, h=None):
  408. h = memoize(h or problem.h, 'h')
  409.  
  410. def RBFS(problem, node, flimit):
  411. if problem.goal_test(node.state):
  412. return node, 0 # (The second value is immaterial)
  413. successors = node.expand(problem)
  414. if len(successors) == 0:
  415. return None, infinity
  416. for s in successors:
  417. s.f = max(s.path_cost + h(s), node.f)
  418. while True:
  419. # Order by lowest f value
  420. successors.sort(key=lambda x: x.f)
  421. best = successors[0]
  422. if best.f > flimit:
  423. return None, best.f
  424. if len(successors) > 1:
  425. alternative = successors[1].f
  426. else:
  427. alternative = infinity
  428. result, best.f = RBFS(problem, best, min(flimit, alternative))
  429. if result is not None:
  430. return result, best.f
  431.  
  432. node = Node(problem.initial)
  433. node.f = h(node)
  434. result, bestf = RBFS(problem, node, infinity)
  435. return result
  436.  
  437.  
  438. # Python modul vo koj se implementirani algoritmite za informirano prebaruvanje
  439.  
  440. # ______________________________________________________________________________________________
  441. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  442.  
  443. import sys
  444. import bisect
  445.  
  446. infinity = float('inf') # sistemski definirana vrednost za beskonecnost
  447.  
  448.  
  449. # ______________________________________________________________________________________________
  450. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  451.  
  452. class Queue:
  453. """Queue is an abstract class/interface. There are three types:
  454. Stack(): A Last In First Out Queue.
  455. FIFOQueue(): A First In First Out Queue.
  456. PriorityQueue(order, f): Queue in sorted order (default min-first).
  457. Each type supports the following methods and functions:
  458. q.append(item) -- add an item to the queue
  459. q.extend(items) -- equivalent to: for item in items: q.append(item)
  460. q.pop() -- return the top item from the queue
  461. len(q) -- number of items in q (also q.__len())
  462. item in q -- does q contain item?
  463. Note that isinstance(Stack(), Queue) is false, because we implement stacks
  464. as lists. If Python ever gets interfaces, Queue will be an interface."""
  465.  
  466. def __init__(self):
  467. raise NotImplementedError
  468.  
  469. def extend(self, items):
  470. for item in items:
  471. self.append(item)
  472.  
  473.  
  474. def Stack():
  475. """A Last-In-First-Out Queue."""
  476. return []
  477.  
  478.  
  479. class FIFOQueue(Queue):
  480. """A First-In-First-Out Queue."""
  481.  
  482. def __init__(self):
  483. self.A = []
  484. self.start = 0
  485.  
  486. def append(self, item):
  487. self.A.append(item)
  488.  
  489. def __len__(self):
  490. return len(self.A) - self.start
  491.  
  492. def extend(self, items):
  493. self.A.extend(items)
  494.  
  495. def pop(self):
  496. e = self.A[self.start]
  497. self.start += 1
  498. if self.start > 5 and self.start > len(self.A) / 2:
  499. self.A = self.A[self.start:]
  500. self.start = 0
  501. return e
  502.  
  503. def __contains__(self, item):
  504. return item in self.A[self.start:]
  505.  
  506.  
  507. class PriorityQueue(Queue):
  508. """A queue in which the minimum (or maximum) element (as determined by f and
  509. order) is returned first. If order is min, the item with minimum f(x) is
  510. returned first; if order is max, then it is the item with maximum f(x).
  511. Also supports dict-like lookup. This structure will be most useful in informed searches"""
  512.  
  513. def __init__(self, order=min, f=lambda x: x):
  514. self.A = []
  515. self.order = order
  516. self.f = f
  517.  
  518. def append(self, item):
  519. bisect.insort(self.A, (self.f(item), item))
  520.  
  521. def __len__(self):
  522. return len(self.A)
  523.  
  524. def pop(self):
  525. if self.order == min:
  526. return self.A.pop(0)[1]
  527. else:
  528. return self.A.pop()[1]
  529.  
  530. def __contains__(self, item):
  531. return any(item == pair[1] for pair in self.A)
  532.  
  533. def __getitem__(self, key):
  534. for _, item in self.A:
  535. if item == key:
  536. return item
  537.  
  538. def __delitem__(self, key):
  539. for i, (value, item) in enumerate(self.A):
  540. if item == key:
  541. self.A.pop(i)
  542.  
  543.  
  544. # ______________________________________________________________________________________________
  545. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  546. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  547. # na sekoj eden problem sto sakame da go resime
  548.  
  549.  
  550. class Problem:
  551. """The abstract class for a formal problem. You should subclass this and
  552. implement the method successor, and possibly __init__, goal_test, and
  553. path_cost. Then you will create instances of your subclass and solve them
  554. with the various search functions."""
  555.  
  556. def __init__(self, initial, goal=None):
  557. """The constructor specifies the initial state, and possibly a goal
  558. state, if there is a unique goal. Your subclass's constructor can add
  559. other arguments."""
  560. self.initial = initial
  561. self.goal = goal
  562.  
  563. def successor(self, state):
  564. """Given a state, return a dictionary of {action : state} pairs reachable
  565. from this state. If there are many successors, consider an iterator
  566. that yields the successors one at a time, rather than building them
  567. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  568. raise NotImplementedError
  569.  
  570. def actions(self, state):
  571. """Given a state, return a list of all actions possible from that state"""
  572. raise NotImplementedError
  573.  
  574. def result(self, state, action):
  575. """Given a state and action, return the resulting state"""
  576. raise NotImplementedError
  577.  
  578. def goal_test(self, state):
  579. """Return True if the state is a goal. The default method compares the
  580. state to self.goal, as specified in the constructor. Implement this
  581. method if checking against a single self.goal is not enough."""
  582. return state == self.goal
  583.  
  584. def path_cost(self, c, state1, action, state2):
  585. """Return the cost of a solution path that arrives at state2 from
  586. state1 via action, assuming cost c to get up to state1. If the problem
  587. is such that the path doesn't matter, this function will only look at
  588. state2. If the path does matter, it will consider c and maybe state1
  589. and action. The default method costs 1 for every step in the path."""
  590. return c + 1
  591.  
  592. def value(self):
  593. """For optimization problems, each state has a value. Hill-climbing
  594. and related algorithms try to maximize this value."""
  595. raise NotImplementedError
  596.  
  597.  
  598. # ______________________________________________________________________________
  599. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  600. # Klasata Node ne se nasleduva
  601.  
  602. class Node:
  603. """A node in a search tree. Contains a pointer to the parent (the node
  604. that this is a successor of) and to the actual state for this node. Note
  605. that if a state is arrived at by two paths, then there are two nodes with
  606. the same state. Also includes the action that got us to this state, and
  607. the total path_cost (also known as g) to reach the node. Other functions
  608. may add an f and h value; see best_first_graph_search and astar_search for
  609. an explanation of how the f and h values are handled. You will not need to
  610. subclass this class."""
  611.  
  612. def __init__(self, state, parent=None, action=None, path_cost=0):
  613. "Create a search tree Node, derived from a parent by an action."
  614. self.state = state
  615. self.parent = parent
  616. self.action = action
  617. self.path_cost = path_cost
  618. self.depth = 0
  619. if parent:
  620. self.depth = parent.depth + 1
  621.  
  622. def __repr__(self):
  623. return "<Node %s>" % (self.state,)
  624.  
  625. def __lt__(self, node):
  626. return self.state < node.state
  627.  
  628. def expand(self, problem):
  629. "List the nodes reachable in one step from this node."
  630. return [self.child_node(problem, action)
  631. for action in problem.actions(self.state)]
  632.  
  633. def child_node(self, problem, action):
  634. "Return a child node from this node"
  635. next = problem.result(self.state, action)
  636. return Node(next, self, action,
  637. problem.path_cost(self.path_cost, self.state,
  638. action, next))
  639.  
  640. def solution(self):
  641. "Return the sequence of actions to go from the root to this node."
  642. return [node.action for node in self.path()[1:]]
  643.  
  644. def solve(self):
  645. "Return the sequence of states to go from the root to this node."
  646. return [node.state for node in self.path()[0:]]
  647.  
  648. def path(self):
  649. "Return a list of nodes forming the path from the root to this node."
  650. x, result = self, []
  651. while x:
  652. result.append(x)
  653. x = x.parent
  654. return list(reversed(result))
  655.  
  656. # We want for a queue of nodes in breadth_first_search or
  657. # astar_search to have no duplicated states, so we treat nodes
  658. # with the same state as equal. [Problem: this may not be what you
  659. # want in other contexts.]
  660.  
  661. def __eq__(self, other):
  662. return isinstance(other, Node) and self.state == other.state
  663.  
  664. def __hash__(self):
  665. return hash(self.state)
  666.  
  667.  
  668.  
  669. # ________________________________________________________________________________________________________
  670. #Pomosna funkcija za informirani prebaruvanja
  671. #So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  672.  
  673. def memoize(fn, slot=None):
  674. """Memoize fn: make it remember the computed value for any argument list.
  675. If slot is specified, store result in that slot of first argument.
  676. If slot is false, store results in a dictionary."""
  677. if slot:
  678. def memoized_fn(obj, *args):
  679. if hasattr(obj, slot):
  680. return getattr(obj, slot)
  681. else:
  682. val = fn(obj, *args)
  683. setattr(obj, slot, val)
  684. return val
  685. else:
  686. def memoized_fn(*args):
  687. if not memoized_fn.cache.has_key(args):
  688. memoized_fn.cache[args] = fn(*args)
  689. return memoized_fn.cache[args]
  690.  
  691. memoized_fn.cache = {}
  692. return memoized_fn
  693.  
  694.  
  695. # ________________________________________________________________________________________________________
  696. #Informirano prebaruvanje vo ramki na graf
  697.  
  698. def best_first_graph_search(problem, f):
  699. """Search the nodes with the lowest f scores first.
  700. You specify the function f(node) that you want to minimize; for example,
  701. if f is a heuristic estimate to the goal, then we have greedy best
  702. first search; if f is node.depth then we have breadth-first search.
  703. There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  704. values will be cached on the nodes as they are computed. So after doing
  705. a best first search you can examine the f values of the path returned."""
  706.  
  707. f = memoize(f, 'f')
  708. node = Node(problem.initial)
  709. if problem.goal_test(node.state):
  710. return node
  711. frontier = PriorityQueue(min, f)
  712. frontier.append(node)
  713. explored = set()
  714. while frontier:
  715. node = frontier.pop()
  716. if problem.goal_test(node.state):
  717. return node
  718. explored.add(node.state)
  719. for child in node.expand(problem):
  720. if child.state not in explored and child not in frontier:
  721. frontier.append(child)
  722. elif child in frontier:
  723. incumbent = frontier[child]
  724. if f(child) < f(incumbent):
  725. del frontier[incumbent]
  726. frontier.append(child)
  727. return None
  728.  
  729.  
  730. def greedy_best_first_graph_search(problem, h=None):
  731. "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  732. h = memoize(h or problem.h, 'h')
  733. return best_first_graph_search(problem, h)
  734.  
  735.  
  736. def astar_search(problem, h=None):
  737. "A* search is best-first graph search with f(n) = g(n)+h(n)."
  738. h = memoize(h or problem.h, 'h')
  739. return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  740.  
  741.  
  742. # ________________________________________________________________________________________________________
  743. #Dopolnitelni prebaruvanja
  744. #Recursive_best_first_search e implementiran
  745. #Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  746.  
  747. def recursive_best_first_search(problem, h=None):
  748. h = memoize(h or problem.h, 'h')
  749.  
  750. def RBFS(problem, node, flimit):
  751. if problem.goal_test(node.state):
  752. return node, 0 # (The second value is immaterial)
  753. successors = node.expand(problem)
  754. if len(successors) == 0:
  755. return None, infinity
  756. for s in successors:
  757. s.f = max(s.path_cost + h(s), node.f)
  758. while True:
  759. # Order by lowest f value
  760. successors.sort(key=lambda x: x.f)
  761. best = successors[0]
  762. if best.f > flimit:
  763. return None, best.f
  764. if len(successors) > 1:
  765. alternative = successors[1].f
  766. else:
  767. alternative = infinity
  768. result, best.f = RBFS(problem, best, min(flimit, alternative))
  769. if result is not None:
  770. return result, best.f
  771.  
  772. node = Node(problem.initial)
  773. node.f = h(node)
  774. result, bestf = RBFS(problem, node, infinity)
  775. return result
  776.  
  777.  
  778.  
  779. # _________________________________________________________________________________________________________
  780. #Vcituvanje na vleznite argumenti za test primerite
  781.  
  782. def precka1(P):
  783. x=P[0]
  784. y=P[1]
  785. n=P[2]
  786.  
  787. if x==2 and y==0 and n==-1:
  788. x=x
  789. y=y+1
  790. n=n*(-1)
  791. elif x==2 and y==4 and n==+1:
  792. x=x
  793. y=y-1
  794. n=n*(-1)
  795. else:
  796. x=x
  797. y=y+n
  798. n=n
  799.  
  800. Pnew=x,y,n
  801. return Pnew
  802.  
  803. def precka2(P):
  804. x=P[0]
  805. y=P[1]
  806. n=P[2]
  807. if x==9 and y==1 and n==-1:
  808. x=x-1
  809. y=y+1
  810. n=n*(-1)
  811. elif x==5 and y==5 and n==+1:
  812. x=x+1
  813. y=y-1
  814. n=n*(-1)
  815. else:
  816. x=x-n
  817. y=y+n
  818. n=n
  819.  
  820. Pnew=x,y,n
  821. return Pnew
  822.  
  823. def precka3(P):
  824. x=P[0]
  825. y=P[1]
  826. n=P[2]
  827.  
  828. if x==6 and y==8 and n==-1:
  829. x=x+1
  830. y=y
  831. n=n*(-1)
  832. elif x==10 and y==8 and n==+1:
  833. x=x-1
  834. y=y
  835. n=n*(-1)
  836. else:
  837. x=x+n
  838. y=y
  839. n=n
  840.  
  841. Pnew=x,y,n
  842. return Pnew
  843.  
  844. def validno(V):
  845. Cx=V[0]
  846. Cy=V[1]
  847. p1x=V[2]
  848. p1y=V[3]
  849. p2x=V[4]
  850. p2y=V[5]
  851. p3x=V[6]
  852. p3y=V[7]
  853.  
  854. t=False
  855. 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):
  856. t=True
  857. else:
  858. t=False
  859. return t
  860.  
  861.  
  862. class PP(Problem):
  863.  
  864. def __init__(self, initial, goal):
  865. self.initial = initial
  866. self.goal = goal
  867.  
  868. def successor(self, state):
  869. succs = dict()
  870.  
  871. x=state[0]
  872. y=state[1]
  873. p1=(state[2],state[3],state[4])
  874. p2=(state[5],state[6],state[7])
  875. p3=(state[8],state[9],state[10])
  876.  
  877. if (y<5 and y>=0 and x >=0 and x<5) or (y<10 and y>=0 and x>4 and x<11):
  878. Xnew=x
  879. Ynew=y+1
  880. p1New=precka1(p1)
  881. p2New=precka2(p2)
  882. p3New=precka3(p3)
  883. V=(Xnew,Ynew,p1New[0],p1New[1],p2New[0],p2New[1],p3New[0],p3New[1])
  884. v=validno(V)
  885. if(v==True):
  886. StateNew=(Xnew,Ynew,p1New[0],p1New[1],p1New[2],p2New[0],p2New[1],p2New[2],p3New[0],p3New[1],p3New[2])
  887. succs['Desno']=StateNew
  888.  
  889. if (y>0 and y<6 and x>=0 and x<5) or (y>0 and y<11 and x>4 and x<11):
  890. Xnew=x
  891. Ynew=y-1
  892. p1New=precka1(p1)
  893. p2New=precka2(p2)
  894. p3New=precka3(p3)
  895. V=(Xnew,Ynew,p1New[0],p1New[1],p2New[0],p2New[1],p3New[0],p3New[1])
  896. v=validno(V)
  897. if(v==True):
  898. StateNew=(Xnew,Ynew,p1New[0],p1New[1],p1New[2],p2New[0],p2New[1],p2New[2],p3New[0],p3New[1],p3New[2])
  899. succs['Levo']=StateNew
  900.  
  901.  
  902. if (x>0 and x<11 and y>=0 and y<6) or (x>5 and x<11 and y>5 and y<11):
  903. Xnew=x-1
  904. Ynew=y
  905. p1New=precka1(p1)
  906. p2New=precka2(p2)
  907. p3New=precka3(p3)
  908. V=(Xnew,Ynew,p1New[0],p1New[1],p2New[0],p2New[1],p3New[0],p3New[1])
  909. v=validno(V)
  910. if(v==True):
  911. StateNew=(Xnew,Ynew,p1New[0],p1New[1],p1New[2],p2New[0],p2New[1],p2New[2],p3New[0],p3New[1],p3New[2])
  912. succs['Gore']=StateNew
  913.  
  914. if (x<10 and x>=0 and y>=0 and y<6) or (x<10 and x>4 and y>5 and y<11):
  915. Xnew=x+1
  916. Ynew=y
  917. p1New=precka1(p1)
  918. p2New=precka2(p2)
  919. p3New=precka3(p3)
  920. V=(Xnew,Ynew,p1New[0],p1New[1],p2New[0],p2New[1],p3New[0],p3New[1])
  921. v=validno(V)
  922. if(v==True):
  923. StateNew=(Xnew,Ynew,p1New[0],p1New[1],p1New[2],p2New[0],p2New[1],p2New[2],p3New[0],p3New[1],p3New[2])
  924. succs['Dolu']=StateNew
  925.  
  926. return succs
  927.  
  928.  
  929. def actions(self, state):
  930. return self.successor(state).keys()
  931.  
  932. def result(self, state, action):
  933. possible = self.successor(state)
  934. return possible[action]
  935.  
  936. def goal_test(self, state):
  937. G = self.goal
  938. return (state[0] == G[0] and state[1] == G[1])
  939.  
  940. def h(self, node):
  941. s=node.state
  942. return abs(s[0] - self.goal[0]) + abs(s[1] - self.goal[1])
  943.  
  944.  
  945.  
  946. CoveceRedica = int(input())
  947. CoveceKolona = int(input())
  948. KukaRedica = int(input())
  949. KukaKolona = int(input())
  950.  
  951. K = [KukaRedica,KukaKolona]
  952. PPinstanca = PP((CoveceRedica, CoveceKolona, 2, 2, -1, 7, 3, +1, 8, 8, +1), K)
  953. answer = astar_search(PPinstanca)
  954. print answer.solution()
Add Comment
Please, Sign In to add comment