Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.38 KB | None | 0 0
  1. import sys
  2. import bisect
  3.  
  4. infinity = float('inf') # sistemski definirana vrednost za beskonecnost
  5.  
  6.  
  7. # ______________________________________________________________________________________________
  8. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  9.  
  10. class Queue:
  11. """Queue is an abstract class/interface. There are three types:
  12. Stack(): A Last In First Out Queue.
  13. FIFOQueue(): A First In First Out Queue.
  14. PriorityQueue(order, f): Queue in sorted order (default min-first).
  15. Each type supports the following methods and functions:
  16. q.append(item) -- add an item to the queue
  17. q.extend(items) -- equivalent to: for item in items: q.append(item)
  18. q.pop() -- return the top item from the queue
  19. len(q) -- number of items in q (also q.__len())
  20. item in q -- does q contain item?
  21. Note that isinstance(Stack(), Queue) is false, because we implement stacks
  22. as lists. If Python ever gets interfaces, Queue will be an interface."""
  23.  
  24. def __init__(self):
  25. raise NotImplementedError
  26.  
  27. def extend(self, items):
  28. for item in items:
  29. self.append(item)
  30.  
  31.  
  32. def Stack():
  33. """A Last-In-First-Out Queue."""
  34. return []
  35.  
  36.  
  37. class FIFOQueue(Queue):
  38. """A First-In-First-Out Queue."""
  39.  
  40. def __init__(self):
  41. self.A = []
  42. self.start = 0
  43.  
  44. def append(self, item):
  45. self.A.append(item)
  46.  
  47. def __len__(self):
  48. return len(self.A) - self.start
  49.  
  50. def extend(self, items):
  51. self.A.extend(items)
  52.  
  53. def pop(self):
  54. e = self.A[self.start]
  55. self.start += 1
  56. if self.start > 5 and self.start > len(self.A) / 2:
  57. self.A = self.A[self.start:]
  58. self.start = 0
  59. return e
  60.  
  61. def __contains__(self, item):
  62. return item in self.A[self.start:]
  63.  
  64.  
  65. class PriorityQueue(Queue):
  66. """A queue in which the minimum (or maximum) element (as determined by f and
  67. order) is returned first. If order is min, the item with minimum f(x) is
  68. returned first; if order is max, then it is the item with maximum f(x).
  69. Also supports dict-like lookup. This structure will be most useful in informed searches"""
  70.  
  71. def __init__(self, order=min, f=lambda x: x):
  72. self.A = []
  73. self.order = order
  74. self.f = f
  75.  
  76. def append(self, item):
  77. bisect.insort(self.A, (self.f(item), item))
  78.  
  79. def __len__(self):
  80. return len(self.A)
  81.  
  82. def pop(self):
  83. if self.order == min:
  84. return self.A.pop(0)[1]
  85. else:
  86. return self.A.pop()[1]
  87.  
  88. def __contains__(self, item):
  89. return any(item == pair[1] for pair in self.A)
  90.  
  91. def __getitem__(self, key):
  92. for _, item in self.A:
  93. if item == key:
  94. return item
  95.  
  96. def __delitem__(self, key):
  97. for i, (value, item) in enumerate(self.A):
  98. if item == key:
  99. self.A.pop(i)
  100.  
  101.  
  102. # ______________________________________________________________________________________________
  103. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  104. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  105. # na sekoj eden problem sto sakame da go resime
  106.  
  107.  
  108. class Problem:
  109. """The abstract class for a formal problem. You should subclass this and
  110. implement the method successor, and possibly __init__, goal_test, and
  111. path_cost. Then you will create instances of your subclass and solve them
  112. with the various search functions."""
  113.  
  114. def __init__(self, initial, goal=None):
  115. """The constructor specifies the initial state, and possibly a goal
  116. state, if there is a unique goal. Your subclass's constructor can add
  117. other arguments."""
  118. self.initial = initial
  119. self.goal = goal
  120.  
  121. def successor(self, state):
  122. """Given a state, return a dictionary of {action : state} pairs reachable
  123. from this state. If there are many successors, consider an iterator
  124. that yields the successors one at a time, rather than building them
  125. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  126. raise NotImplementedError
  127.  
  128. def actions(self, state):
  129. """Given a state, return a list of all actions possible from that state"""
  130. raise NotImplementedError
  131.  
  132. def result(self, state, action):
  133. """Given a state and action, return the resulting state"""
  134. raise NotImplementedError
  135.  
  136. def goal_test(self, state):
  137. """Return True if the state is a goal. The default method compares the
  138. state to self.goal, as specified in the constructor. Implement this
  139. method if checking against a single self.goal is not enough."""
  140. return state == self.goal
  141.  
  142. def path_cost(self, c, state1, action, state2):
  143. """Return the cost of a solution path that arrives at state2 from
  144. state1 via action, assuming cost c to get up to state1. If the problem
  145. is such that the path doesn't matter, this function will only look at
  146. state2. If the path does matter, it will consider c and maybe state1
  147. and action. The default method costs 1 for every step in the path."""
  148. return c + 1
  149.  
  150. def value(self):
  151. """For optimization problems, each state has a value. Hill-climbing
  152. and related algorithms try to maximize this value."""
  153. raise NotImplementedError
  154.  
  155.  
  156. # ______________________________________________________________________________
  157. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  158. # Klasata Node ne se nasleduva
  159.  
  160. class Node:
  161. """A node in a search tree. Contains a pointer to the parent (the node
  162. that this is a successor of) and to the actual state for this node. Note
  163. that if a state is arrived at by two paths, then there are two nodes with
  164. the same state. Also includes the action that got us to this state, and
  165. the total path_cost (also known as g) to reach the node. Other functions
  166. may add an f and h value; see best_first_graph_search and astar_search for
  167. an explanation of how the f and h values are handled. You will not need to
  168. subclass this class."""
  169.  
  170. def __init__(self, state, parent=None, action=None, path_cost=0):
  171. "Create a search tree Node, derived from a parent by an action."
  172. self.state = state
  173. self.parent = parent
  174. self.action = action
  175. self.path_cost = path_cost
  176. self.depth = 0
  177. if parent:
  178. self.depth = parent.depth + 1
  179.  
  180. def __repr__(self):
  181. return "<Node %s>" % (self.state,)
  182.  
  183. def __lt__(self, node):
  184. return self.state < node.state
  185.  
  186. def expand(self, problem):
  187. "List the nodes reachable in one step from this node."
  188. return [self.child_node(problem, action)
  189. for action in problem.actions(self.state)]
  190.  
  191. def child_node(self, problem, action):
  192. "Return a child node from this node"
  193. next = problem.result(self.state, action)
  194. return Node(next, self, action,
  195. problem.path_cost(self.path_cost, self.state,
  196. action, next))
  197.  
  198. def solution(self):
  199. "Return the sequence of actions to go from the root to this node."
  200. return [node.action for node in self.path()[1:]]
  201.  
  202. def solve(self):
  203. "Return the sequence of states to go from the root to this node."
  204. return [node.state for node in self.path()[0:]]
  205.  
  206. def path(self):
  207. "Return a list of nodes forming the path from the root to this node."
  208. x, result = self, []
  209. while x:
  210. result.append(x)
  211. x = x.parent
  212. return list(reversed(result))
  213.  
  214. # We want for a queue of nodes in breadth_first_search or
  215. # astar_search to have no duplicated states, so we treat nodes
  216. # with the same state as equal. [Problem: this may not be what you
  217. # want in other contexts.]
  218.  
  219. def __eq__(self, other):
  220. return isinstance(other, Node) and self.state == other.state
  221.  
  222. def __hash__(self):
  223. return hash(self.state)
  224.  
  225.  
  226. # ________________________________________________________________________________________________________
  227. # Pomosna funkcija za informirani prebaruvanja
  228. # So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  229.  
  230. def memoize(fn, slot=None):
  231. """Memoize fn: make it remember the computed value for any argument list.
  232. If slot is specified, store result in that slot of first argument.
  233. If slot is false, store results in a dictionary."""
  234. if slot:
  235. def memoized_fn(obj, *args):
  236. if hasattr(obj, slot):
  237. return getattr(obj, slot)
  238. else:
  239. val = fn(obj, *args)
  240. setattr(obj, slot, val)
  241. return val
  242. else:
  243. def memoized_fn(*args):
  244. if not memoized_fn.cache.has_key(args):
  245. memoized_fn.cache[args] = fn(*args)
  246. return memoized_fn.cache[args]
  247.  
  248. memoized_fn.cache = {}
  249. return memoized_fn
  250.  
  251.  
  252. # ________________________________________________________________________________________________________
  253. # Informirano prebaruvanje vo ramki na graf
  254.  
  255. def best_first_graph_search(problem, f):
  256. """Search the nodes with the lowest f scores first.
  257. You specify the function f(node) that you want to minimize; for example,
  258. if f is a heuristic estimate to the goal, then we have greedy best
  259. first search; if f is node.depth then we have breadth-first search.
  260. There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  261. values will be cached on the nodes as they are computed. So after doing
  262. a best first search you can examine the f values of the path returned."""
  263.  
  264. f = memoize(f, 'f')
  265. node = Node(problem.initial)
  266. if problem.goal_test(node.state):
  267. return node
  268. frontier = PriorityQueue(min, f)
  269. frontier.append(node)
  270. explored = set()
  271. while frontier:
  272. node = frontier.pop()
  273. if problem.goal_test(node.state):
  274. return node
  275. explored.add(node.state)
  276. for child in node.expand(problem):
  277. if child.state not in explored and child not in frontier:
  278. frontier.append(child)
  279. elif child in frontier:
  280. incumbent = frontier[child]
  281. if f(child) < f(incumbent):
  282. del frontier[incumbent]
  283. frontier.append(child)
  284. return None
  285.  
  286.  
  287. def greedy_best_first_graph_search(problem, h=None):
  288. "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  289. h = memoize(h or problem.h, 'h')
  290. return best_first_graph_search(problem, h)
  291.  
  292.  
  293. def astar_search(problem, h=None):
  294. "A* search is best-first graph search with f(n) = g(n)+h(n)."
  295. h = memoize(h or problem.h, 'h')
  296. return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  297.  
  298.  
  299. # ________________________________________________________________________________________________________
  300. # Dopolnitelni prebaruvanja
  301. # Recursive_best_first_search e implementiran
  302. # Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  303.  
  304. def recursive_best_first_search(problem, h=None):
  305. h = memoize(h or problem.h, 'h')
  306.  
  307. def RBFS(problem, node, flimit):
  308. if problem.goal_test(node.state):
  309. return node, 0 # (The second value is immaterial)
  310. successors = node.expand(problem)
  311. if len(successors) == 0:
  312. return None, infinity
  313. for s in successors:
  314. s.f = max(s.path_cost + h(s), node.f)
  315. while True:
  316. # Order by lowest f value
  317. successors.sort(key=lambda x: x.f)
  318. best = successors[0]
  319. if best.f > flimit:
  320. return None, best.f
  321. if len(successors) > 1:
  322. alternative = successors[1].f
  323. else:
  324. alternative = infinity
  325. result, best.f = RBFS(problem, best, min(flimit, alternative))
  326. if result is not None:
  327. return result, best.f
  328.  
  329. node = Node(problem.initial)
  330. node.f = h(node)
  331. result, bestf = RBFS(problem, node, infinity)
  332. return result
  333.  
  334.  
  335. def update_p1(p1):
  336. x, y, n = p1 # go proveruvame levoto kvadratce
  337. if (y == 0 and n == -1) or (y == 4 and n == 1):
  338. n *= -1
  339. y_new = y + n
  340. return x, y_new, n
  341.  
  342.  
  343. def update_p2(p2):
  344. x, y, n = p2 # go proveruvame gornoto levo kvadratce
  345. if (x == 5 and n == -1) or (x == 9 and n == 1):
  346. n *= -1
  347. x_new = x + n
  348. y_new = y - n
  349. return x_new, y_new, n
  350.  
  351.  
  352. def update_p3(p3):
  353. x, y, n = p3 # go proveruvame gornoto kvadratce
  354. if (x == 5 and n == -1) or (x == 9 and n == 1):
  355. n *= -1
  356. x_new = x + n
  357. return x_new, y, n
  358.  
  359.  
  360. def isValid(x, y, p1, p2, p3):
  361.  
  362. if x < 0 or y < 0 or x > 10 or y > 10:
  363. return False
  364. if y > 5 and x < 5:
  365. return False
  366.  
  367.  
  368. if (x == p1[0] and y == p1[1]) or (x == p1[0] and (y == p1[1] + 1)):
  369. return False
  370. if (x == p2[0] and y == p2[1]) or (x == p2[0] + 1 and y == p2[1]) or (x == p2[0] and y == p2[1] + 1) or (
  371. x == p2[0] + 1 and y == p2[1] + 1):
  372. return False
  373. if (x == p3[0] and y == p3[1]) or (x == p3[0] + 1 and y == p3[1]):
  374. return False
  375.  
  376. return True
  377.  
  378.  
  379. class Istrazhucah(Problem):
  380.  
  381. def __init__(self, initial=None, goal=None):
  382. self.initial = initial
  383. self.goal = goal
  384.  
  385.  
  386. def successor(self, state):
  387. successors = dict()
  388. x, y = state[0]
  389. p1 = state[1]
  390. p2 = state[2]
  391. p3 = state[3]
  392. p1_new = update_p1(p1)
  393. p2_new = update_p2(p2)
  394. p3_new = update_p3(p3)
  395.  
  396. # Desno
  397. y_new = y + 1
  398. if isValid(x, y_new, p1_new, p2_new, p3_new):
  399. state_new = ((x, y_new), p1_new, p2_new, p3_new)
  400. successors['Desno'] = state_new
  401. # Levo
  402. y_new = y - 1
  403. if isValid(x, y_new, p1_new, p2_new, p3_new):
  404. state_new = ((x, y_new), p1_new, p2_new, p3_new)
  405. successors['Levo'] = state_new
  406.  
  407. # Gore
  408. x_new = x - 1
  409. if isValid(x_new, y, p1_new, p2_new, p3_new):
  410. state_new = ((x_new, y), p1_new, p2_new, p3_new)
  411. successors['Gore'] = state_new
  412.  
  413. # Dolu
  414. x_new = x + 1
  415. if isValid(x_new, y, p1_new, p2_new, p3_new):
  416. state_new = ((x_new, y), p1_new, p2_new, p3_new)
  417. successors['Dolu'] = state_new
  418.  
  419. return successors
  420.  
  421. def actions(self, state):
  422. return self.successor(state).keys()
  423.  
  424.  
  425. def goal_test(self, state):
  426. g = self.goal
  427. x, y = state[0]
  428. return x == g[0] and y == g[1]
  429.  
  430. def path_cost(self, c, state1, action, state2):
  431. """Return the cost of a solution path that arrives at state2 from
  432. state1 via action, assuming cost c to get up to state1. If the problem
  433. is such that the path doesn't matter, this function will only look at
  434. state2. If the path does matter, it will consider c and maybe state1
  435. and action. The default method costs 1 for every step in the path."""
  436. return c + 1
  437.  
  438.  
  439. def result(self, state, action):
  440. possible = self.successor(state)
  441. return possible[action]
  442.  
  443. def h(self, node):
  444. """Funkcija koja ja presmetuva hevristikata,
  445. t.e. Menheten rastojanieto pomegu nekoj tekoven jazel od prebaruvanjeto i celniot jazel"""
  446. #x1, y1 = self.initial[0]
  447. s = node.state
  448. g = self.goal
  449. return mhd(s[0],g)
  450.  
  451. def mhd(covece, cel):
  452. x1, y1 = covece
  453. x2, y2 = cel
  454. return abs(x1 - x2) + abs(y1 - y2)
  455.  
  456.  
  457.  
  458. # Vcituvanje na vleznite argumenti za test primerite
  459.  
  460. CoveceRedica = int(input())
  461. CoveceKolona = int(input())
  462. KukaRedica = int(input())
  463. KukaKolona = int(input())
  464.  
  465. # Vasiot kod pisuvajte go pod ovoj komentar
  466.  
  467. Covece = (CoveceRedica, CoveceKolona)
  468. goal = (KukaRedica, KukaKolona)
  469. p1 = (2, 2, -1)
  470. p2 = (7, 2, -1)
  471. p3 = (7, 8, 1)
  472. initial = (Covece, p1, p2, p3)
  473.  
  474. #Coveche = Istrazhucah(((CoveceRedica, CoveceKolona), (2, 2, -1), (7, 2, -1), (7, 8, 1))(KukaRedica, KukaKolona))
  475. IstrazhucahInst = Istrazhucah(initial,goal)
  476.  
  477. answer = astar_search(IstrazhucahInst).solution()
  478. print(answer)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement