Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.30 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. # Neinformirano prebaruvanje vo ramki na drvo
  228. # Vo ramki na drvoto ne razresuvame jamki
  229.  
  230. def tree_search(problem, fringe):
  231. """Search through the successors of a problem to find a goal.
  232. The argument fringe should be an empty queue."""
  233. fringe.append(Node(problem.initial))
  234. while fringe:
  235. node = fringe.pop()
  236. print(node.state)
  237. if problem.goal_test(node.state):
  238. return node
  239. fringe.extend(node.expand(problem))
  240. return None
  241.  
  242.  
  243. def breadth_first_tree_search(problem):
  244. "Search the shallowest nodes in the search tree first."
  245. return tree_search(problem, FIFOQueue())
  246.  
  247.  
  248. def depth_first_tree_search(problem):
  249. "Search the deepest nodes in the search tree first."
  250. return tree_search(problem, Stack())
  251.  
  252.  
  253. # ________________________________________________________________________________________________________
  254. # Neinformirano prebaruvanje vo ramki na graf
  255. # Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  256.  
  257. def graph_search(problem, fringe):
  258. """Search through the successors of a problem to find a goal.
  259. The argument fringe should be an empty queue.
  260. If two paths reach a state, only use the best one."""
  261. closed = {}
  262. fringe.append(Node(problem.initial))
  263. while fringe:
  264. node = fringe.pop()
  265. if problem.goal_test(node.state):
  266. return node
  267. if node.state not in closed:
  268. closed[node.state] = True
  269. fringe.extend(node.expand(problem))
  270. return None
  271.  
  272.  
  273. def breadth_first_graph_search(problem):
  274. "Search the shallowest nodes in the search tree first."
  275. return graph_search(problem, FIFOQueue())
  276.  
  277.  
  278. def depth_first_graph_search(problem):
  279. "Search the deepest nodes in the search tree first."
  280. return graph_search(problem, Stack())
  281.  
  282.  
  283. def uniform_cost_search(problem):
  284. "Search the nodes in the search tree with lowest cost first."
  285. return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  286.  
  287.  
  288. def depth_limited_search(problem, limit=50):
  289. "depth first search with limited depth"
  290.  
  291. def recursive_dls(node, problem, limit):
  292. "helper function for depth limited"
  293. cutoff_occurred = False
  294. if problem.goal_test(node.state):
  295. return node
  296. elif node.depth == limit:
  297. return 'cutoff'
  298. else:
  299. for successor in node.expand(problem):
  300. result = recursive_dls(successor, problem, limit)
  301. if result == 'cutoff':
  302. cutoff_occurred = True
  303. elif result != None:
  304. return result
  305. if cutoff_occurred:
  306. return 'cutoff'
  307. else:
  308. return None
  309.  
  310. # Body of depth_limited_search:
  311. return recursive_dls(Node(problem.initial), problem, limit)
  312.  
  313.  
  314. def iterative_deepening_search(problem):
  315. for depth in range(sys.maxint):
  316. result = depth_limited_search(problem, depth)
  317. if result is not 'cutoff':
  318. return result
  319.  
  320.  
  321. # _________________________________________________________________________________________________________
  322. # PRIMER 1 : PROBLEM SO DVA SADA SO VODA
  323. # OPIS: Dadeni se dva sada J0 i J1 so kapaciteti C0 i C1
  324. # Na pocetok dvata sada se polni. Inicijalnata sostojba moze da se prosledi na pocetok
  325. # Problemot e kako da se stigne do sostojba vo koja J0 ke ima G0 litri, a J1 ke ima G1 litri
  326. # AKCII: 1. Da se isprazni bilo koj od sadovite
  327. # 2. Da se prefrli tecnosta od eden sad vo drug so toa sto ne moze da se nadmine kapacitetot na sadovite
  328. # Moze da ima i opcionalen tret vid na akcii 3. Napolni bilo koj od sadovite (studentite da ja implementiraat ovaa varijanta)
  329. # ________________________________________________________________________________________________________
  330.  
  331. class WJ(Problem):
  332. """STATE: Torka od oblik (3,2) if jug J0 has 3 liters and J1 2 liters
  333. Opcionalno moze za nekoj od sadovite da se sretne i vrednost '*' sto znaci deka e nebitno kolku ima vo toj sad
  334. GOAL: Predefinirana sostojba do kade sakame da stigneme. Ako ne interesira samo eden sad za drugiot mozeme da stavime '*'
  335. PROBLEM: Se specificiraat kapacitetite na sadovite, pocetna sostojba i cel """
  336.  
  337. def __init__(self, capacities=(5, 2), initial=(5, 0), goal=(0, 1)):
  338. self.capacities = capacities
  339. self.initial = initial
  340. self.goal = goal
  341.  
  342. def goal_test(self, state):
  343. """ Vraka true ako sostojbata e celna """
  344. g = self.goal
  345. return (state[0] == g[0] or g[0] == '*') and \
  346. (state[1] == g[1] or g[1] == '*')
  347.  
  348. def successor(self, J):
  349. """Vraka recnik od sledbenici na sostojbata"""
  350. successors = dict()
  351. J0, J1 = J
  352. (C0, C1) = self.capacities
  353. if J0 > 0:
  354. Jnew = 0, J1
  355. successors['dump jug 0'] = Jnew
  356. if J1 > 0:
  357. Jnew = J0, 0
  358. successors['dump jug 1'] = Jnew
  359. if J1 < C1 and J0 > 0:
  360. delta = min(J0, C1 - J1)
  361. Jnew = J0 - delta, J1 + delta
  362. successors['pour jug 0 into jug 1'] = Jnew
  363. if J0 < C0 and J1 > 0:
  364. delta = min(J1, C0 - J0)
  365. Jnew = J0 + delta, J1 - delta
  366. successors['pour jug 1 into jug 0'] = Jnew
  367. return successors
  368.  
  369. def actions(self, state):
  370. return self.successor(state).keys()
  371.  
  372. def result(self, state, action):
  373. possible = self.successor(state)
  374. return possible[action]
  375.  
  376.  
  377. def precka1(position):
  378. x1, y1, x2, y2, direction = position
  379. if (y1 == 0 and direction == -1) or (y2 == 5 and direction == 1):
  380. direction = direction * (-1)
  381. y1_new = y1 + direction
  382. y2_new = y2 + direction
  383. position_new = x1, y1_new, x2 , y2_new, direction
  384. return position_new
  385.  
  386. def precka2(position):
  387. x1, y1, x2, y2, x3, y3, x4, y4, direction = position
  388. if((x2 == 5 and y2 == 5 and direction == 1) or (x3==10 and y3 ==0 and direction == -1)):
  389. direction = direction * (-1)
  390. x1_new = x1 - direction
  391. y1_new = y1 + direction
  392. x2_new = x2 - direction
  393. y2_new = y2 + direction
  394. x3_new = x3 - direction
  395. y3_new = y3 + direction
  396. x4_new = x4 - direction
  397. y4_new = y4 + direction
  398. position_new = x1_new, y1_new, x2_new, y2_new, x3_new, y3_new, x4_new, y4_new, direction
  399. return position_new
  400.  
  401. def precka3(position):
  402. x1, y1, x2, y2, direction = position
  403. if((x1 == 5 and direction == -1) or (x2 == 10 and direction == 1)):
  404. direction = direction * (-1)
  405. x1_new = x1 + direction
  406. x2_new = x2 + direction
  407. position_new = x1_new, y1, x2_new, y2, direction
  408. return position_new
  409.  
  410. class Explorer(Problem):
  411.  
  412. def __init__(self, initial, goal):
  413. super().__init__(initial, goal)
  414.  
  415. def goal_test(self, state):
  416. g = self.goal
  417. return state[0] == g[0] and state[1] == g[1]
  418.  
  419. def successor(self, state):
  420. successors = dict()
  421. x = state[0]
  422. y = state[1]
  423. obstacle_1 = (state[2], state[3], state[4], state[5], state[6])
  424. obstacle_2 = (state[7], state[8], state[9], state[10], state[11], state[12], state[13], state[14], state[15])
  425. obstacle_3 = (state[16], state[17], state[18], state[19], state[20])
  426.  
  427. obstacle_1_new = precka1(obstacle_1)
  428. obstacle_2_new = precka2(obstacle_2)
  429. obstacle_3_new = precka3(obstacle_3)
  430.  
  431. # Right
  432. if ((x<5 and y<5) or (x>4 and y<10)):
  433. x_new = x
  434. y_new = y + 1
  435. if (x_new != obstacle_1_new[0] or y_new != obstacle_1_new[1]) and \
  436. (x_new != obstacle_1_new[2] or y_new != obstacle_1_new[3]) and \
  437. (x_new != obstacle_2_new[0] or y_new != obstacle_2_new[1]) and \
  438. (x_new != obstacle_2_new[2] or y_new != obstacle_2_new[3]) and \
  439. (x_new != obstacle_2_new[4] or y_new != obstacle_2_new[5]) and \
  440. (x_new != obstacle_2_new[6] or y_new != obstacle_2_new[7]) and \
  441. (x_new != obstacle_3_new[0] or y_new != obstacle_3_new[1]) and \
  442. (x_new != obstacle_3_new[2] or y_new != obstacle_3_new[3]):
  443. state_new = (x_new, y_new, obstacle_1_new[0], obstacle_1_new[1],
  444. obstacle_1_new[2], obstacle_1_new[3], obstacle_1_new[4],
  445. obstacle_2_new[0], obstacle_2_new[1], obstacle_2_new[2],
  446. obstacle_2_new[3], obstacle_2_new[4], obstacle_2_new[5],
  447. obstacle_2_new[6], obstacle_2_new[7], obstacle_2_new[8],
  448. obstacle_3_new[0], obstacle_3_new[1], obstacle_3_new[2],
  449. obstacle_3_new[3], obstacle_3_new[4])
  450. successors['Desno'] = state_new
  451.  
  452.  
  453. # Left
  454. if y > 0:
  455. x_new = x
  456. y_new = y - 1
  457. if (x_new != obstacle_1_new[0] or y_new != obstacle_1_new[1]) and \
  458. (x_new != obstacle_1_new[2] or y_new != obstacle_1_new[3]) and \
  459. (x_new != obstacle_2_new[0] or y_new != obstacle_2_new[1]) and \
  460. (x_new != obstacle_2_new[2] or y_new != obstacle_2_new[3]) and \
  461. (x_new != obstacle_2_new[4] or y_new != obstacle_2_new[5]) and \
  462. (x_new != obstacle_2_new[6] or y_new != obstacle_2_new[7]) and \
  463. (x_new != obstacle_3_new[0] or y_new != obstacle_3_new[1]) and \
  464. (x_new != obstacle_3_new[2] or y_new != obstacle_3_new[3]):
  465. state_new = (x_new, y_new, obstacle_1_new[0], obstacle_1_new[1],
  466. obstacle_1_new[2], obstacle_1_new[3], obstacle_1_new[4],
  467. obstacle_2_new[0], obstacle_2_new[1], obstacle_2_new[2],
  468. obstacle_2_new[3], obstacle_2_new[4], obstacle_2_new[5],
  469. obstacle_2_new[6], obstacle_2_new[7], obstacle_2_new[8],
  470. obstacle_3_new[0], obstacle_3_new[1], obstacle_3_new[2],
  471. obstacle_3_new[3], obstacle_3_new[4])
  472. successors['Levo'] = state_new
  473.  
  474. # Up
  475. if ((y>5 and x>5) or (y<6 and x>0)):
  476. x_new = x - 1
  477. y_new = y
  478. if (x_new != obstacle_1_new[0] or y_new != obstacle_1_new[1]) and \
  479. (x_new != obstacle_1_new[2] or y_new != obstacle_1_new[3]) and \
  480. (x_new != obstacle_2_new[0] or y_new != obstacle_2_new[1]) and \
  481. (x_new != obstacle_2_new[2] or y_new != obstacle_2_new[3]) and \
  482. (x_new != obstacle_2_new[4] or y_new != obstacle_2_new[5]) and \
  483. (x_new != obstacle_2_new[6] or y_new != obstacle_2_new[7]) and \
  484. (x_new != obstacle_3_new[0] or y_new != obstacle_3_new[1]) and \
  485. (x_new != obstacle_3_new[2] or y_new != obstacle_3_new[3]):
  486. state_new = (x_new, y_new, obstacle_1_new[0], obstacle_1_new[1],
  487. obstacle_1_new[2], obstacle_1_new[3], obstacle_1_new[4],
  488. obstacle_2_new[0], obstacle_2_new[1], obstacle_2_new[2],
  489. obstacle_2_new[3], obstacle_2_new[4], obstacle_2_new[5],
  490. obstacle_2_new[6], obstacle_2_new[7], obstacle_2_new[8],
  491. obstacle_3_new[0], obstacle_3_new[1], obstacle_3_new[2],
  492. obstacle_3_new[3], obstacle_3_new[4])
  493. successors['Gore'] = state_new
  494.  
  495. # Down
  496. if x < 10:
  497.  
  498. x_new = x + 1
  499. y_new = y
  500.  
  501. if (x_new != obstacle_1_new[0] or y_new != obstacle_1_new[1]) and \
  502. (x_new != obstacle_1_new[2] or y_new != obstacle_1_new[3]) and \
  503. (x_new != obstacle_2_new[0] or y_new != obstacle_2_new[1]) and \
  504. (x_new != obstacle_2_new[2] or y_new != obstacle_2_new[3]) and \
  505. (x_new != obstacle_2_new[4] or y_new != obstacle_2_new[5]) and \
  506. (x_new != obstacle_2_new[6] or y_new != obstacle_2_new[7]) and \
  507. (x_new != obstacle_3_new[0] or y_new != obstacle_3_new[1]) and \
  508. (x_new != obstacle_3_new[2] or y_new != obstacle_3_new[3]):
  509. state_new = (x_new, y_new, obstacle_1_new[0], obstacle_1_new[1],
  510. obstacle_1_new[2], obstacle_1_new[3], obstacle_1_new[4],
  511. obstacle_2_new[0], obstacle_2_new[1], obstacle_2_new[2],
  512. obstacle_2_new[3], obstacle_2_new[4], obstacle_2_new[5],
  513. obstacle_2_new[6], obstacle_2_new[7], obstacle_2_new[8],
  514. obstacle_3_new[0], obstacle_3_new[1], obstacle_3_new[2],
  515. obstacle_3_new[3], obstacle_3_new[4])
  516. successors['Dolu'] = state_new
  517.  
  518. return successors
  519.  
  520. def actions(self, state):
  521. return self.successor(state).keys()
  522.  
  523. def result(self, state, action):
  524. possible = self.successor(state)
  525. return possible[action]
  526.  
  527.  
  528. if __name__ == '__main__':
  529. man_row = int(input())
  530. man_column = int(input())
  531. house_row = int(input())
  532. house_column = int(input())
  533.  
  534. house = [house_row, house_column]
  535.  
  536. explorer = Explorer((man_row, man_column, 2, 2, 2, 3, -1, 7, 2, 7, 3, 8, 2, 8, 3, 1, 7, 8, 8, 8, 1), house)
  537.  
  538. answer = breadth_first_graph_search(explorer)
  539. print(answer.solution())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement