Advertisement
NHristovski

Untitled

Apr 2nd, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.24 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,K,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. self.maxPeople = K
  121.  
  122. def successor(self, state):
  123. """Given a state, return a dictionary of {action : state} pairs reachable
  124. from this state. If there are many successors, consider an iterator
  125. that yields the successors one at a time, rather than building them
  126. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  127. raise NotImplementedError
  128.  
  129. def actions(self, state):
  130. """Given a state, return a list of all actions possible from that state"""
  131. raise NotImplementedError
  132.  
  133. def result(self, state, action):
  134. """Given a state and action, return the resulting state"""
  135. raise NotImplementedError
  136.  
  137. def goal_test(self, state):
  138. """Return True if the state is a goal. The default method compares the
  139. state to self.goal, as specified in the constructor. Implement this
  140. method if checking against a single self.goal is not enough."""
  141. return state == self.goal
  142.  
  143. def path_cost(self, c, state1, action, state2):
  144. """Return the cost of a solution path that arrives at state2 from
  145. state1 via action, assuming cost c to get up to state1. If the problem
  146. is such that the path doesn't matter, this function will only look at
  147. state2. If the path does matter, it will consider c and maybe state1
  148. and action. The default method costs 1 for every step in the path."""
  149. return c + 1
  150.  
  151. def value(self):
  152. """For optimization problems, each state has a value. Hill-climbing
  153. and related algorithms try to maximize this value."""
  154. raise NotImplementedError
  155.  
  156.  
  157. # ______________________________________________________________________________
  158. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  159. # Klasata Node ne se nasleduva
  160.  
  161. class Node:
  162. """A node in a search tree. Contains a pointer to the parent (the node
  163. that this is a successor of) and to the actual state for this node. Note
  164. that if a state is arrived at by two paths, then there are two nodes with
  165. the same state. Also includes the action that got us to this state, and
  166. the total path_cost (also known as g) to reach the node. Other functions
  167. may add an f and h value; see best_first_graph_search and astar_search for
  168. an explanation of how the f and h values are handled. You will not need to
  169. subclass this class."""
  170.  
  171. def __init__(self, state, parent=None, action=None, path_cost=0):
  172. "Create a search tree Node, derived from a parent by an action."
  173. self.state = state
  174. self.parent = parent
  175. self.action = action
  176. self.path_cost = path_cost
  177. self.depth = 0
  178. if parent:
  179. self.depth = parent.depth + 1
  180.  
  181. def __repr__(self):
  182. return "<Node %s>" % (self.state,)
  183.  
  184. def __lt__(self, node):
  185. return self.state < node.state
  186.  
  187. def expand(self, problem):
  188. "List the nodes reachable in one step from this node."
  189. return [self.child_node(problem, action)
  190. for action in problem.actions(self.state)]
  191.  
  192. def child_node(self, problem, action):
  193. "Return a child node from this node"
  194. next = problem.result(self.state, action)
  195. return Node(next, self, action,
  196. problem.path_cost(self.path_cost, self.state,
  197. action, next))
  198.  
  199. def solution(self):
  200. "Return the sequence of actions to go from the root to this node."
  201. return [node.action for node in self.path()[1:]]
  202.  
  203. def solve(self):
  204. "Return the sequence of states to go from the root to this node."
  205. return [node.state for node in self.path()[0:]]
  206.  
  207. def path(self):
  208. "Return a list of nodes forming the path from the root to this node."
  209. x, result = self, []
  210. while x:
  211. result.append(x)
  212. x = x.parent
  213. return list(reversed(result))
  214.  
  215. # We want for a queue of nodes in breadth_first_search or
  216. # astar_search to have no duplicated states, so we treat nodes
  217. # with the same state as equal. [Problem: this may not be what you
  218. # want in other contexts.]
  219.  
  220. def __eq__(self, other):
  221. return isinstance(other, Node) and self.state == other.state
  222.  
  223. def __hash__(self):
  224. return hash(self.state)
  225.  
  226.  
  227. def memoize (fn, slot=None):
  228. if slot:
  229. def memoized_fn(obj, *args):
  230. if hasattr(obj,slot):
  231. return getattr(obj,slot)
  232. else:
  233. val = fn(obj, *args)
  234. setattr(obj, slot, val)
  235. return val
  236. else:
  237. def memoized_fn(*args):
  238. if not memoized_fn.cache.has_key(args):
  239. mamoized_fn.cache[args] = fn(*args)
  240. return memoized_fn.cache[args]
  241. memoized_fn.cache = {}
  242. return memoized_fn
  243.  
  244.  
  245. def best_first_graph_search(problem, f):
  246. f = memoize(f, 'f')
  247. node = Node(problem.initial)
  248. if problem.goal_test(node.state):
  249. return node
  250. frontier = PriorityQueue(min, f)
  251. frontier.append(node)
  252. explored = set()
  253. while frontier:
  254. node = frontier.pop()
  255. if problem.goal_test(node.state):
  256. return node
  257. explored.add(node.state)
  258. for child in node.expand(problem):
  259. if child.state not in explored and child not in frontier:
  260. frontier.append(child)
  261. elif child in frontier:
  262. incumbent = frontier[child]
  263. if f(child) < f(incumbent):
  264. del frontier[incumbent]
  265. frontier.append(child)
  266. return None
  267.  
  268. def greedy_best_first_graph_search (problem, h= None):
  269. h = memoize(h or problem.h, 'h')
  270. return best_first_graph_search(problem, h)
  271.  
  272. def astar_search (problem, h= None):
  273. h = memoize(h or problem.h,'h')
  274. return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  275.  
  276. def recursive_best_first_search(problem, h=None):
  277. h = memoize(h or problem.h, 'h')
  278. def RBFS(problem, node, flimit):
  279. if problem.goal_test(node.state):
  280. return node, 0
  281. successors = node.expand(problem)
  282. if len(successors) == 0:
  283. return None, infinity
  284. for s in successors:
  285. s.f= max(s.path_cost+ h(s), node.f)
  286. while True:
  287. successors.sort(key = lambda x: x.f)
  288. best = successors[0]
  289. if best.f> flimit:
  290. return None, best.f
  291. if len(successors) > 1:
  292. alternative = successors[1].f
  293. else:
  294. alternative = infinity
  295. result, best.f= RBFS(problem, best, min(flimit, alternative))
  296. if result is not None:
  297. return result, best.f
  298. node = Node(problem.initial)
  299. node.f = h(node)
  300. result, bestf = RBFS(problem,node,infinity)
  301. return result
  302. #Vcituvanje na vleznite argumenti za test primerite
  303. class MisioneriKanibali(Problem):
  304.  
  305. def init(self,initial,K,goal = None):
  306. self.initial = initial
  307. self.goal = goal
  308. self.numPeople = initial[0]
  309. self.maxPeople = K
  310.  
  311. def goal_test(self, state):
  312. return state[0] == 0 and state[1] == 0 # site da se na desnata strana
  313.  
  314. def successor(self, state):
  315. hashMap = dict()
  316. tempList = []
  317. for x in range(0,self.maxPeople + 1):
  318. for y in range(0,self.maxPeople + 1):
  319. tempList.append((x,y))
  320.  
  321. listActions = []
  322. for (x,y) in tempList:
  323. if (x + y != 0 and x + y <= self.maxPeople):
  324. listActions.append((x,y))
  325.  
  326.  
  327. #print "state"
  328. #print state
  329.  
  330. for (x,y) in listActions:
  331.  
  332. if (state[2] == 'L'):
  333. if (x <= state[0] and y <= state[1]):
  334. newMisioneriL = state[0] - x
  335. newKanibaliL = state[1] - y
  336. newMisioneriD = state[3] + x
  337. newKanibaliD = state[4] + y
  338.  
  339.  
  340. if (newMisioneriL == 0):
  341. if (newMisioneriD >= newKanibaliD):
  342. hashMap["M" + str(x) + "_" + str(y) + "K"] = (newMisioneriL,newKanibaliL,'D',newMisioneriD,newKanibaliD)
  343. elif (newMisioneriD == 0):
  344. if (newMisioneriL >= newKanibaliL):
  345. hashMap["M" + str(x) + "_" + str(y) + "K"] = (newMisioneriL,newKanibaliL,'D',newMisioneriD,newKanibaliD)
  346. elif (newMisioneriL >= newKanibaliL and newMisioneriD >= newKanibaliD):
  347. hashMap["M" + str(x) + "_" + str(y) + "K"] = (newMisioneriL,newKanibaliL,'D',newMisioneriD,newKanibaliD)
  348.  
  349. else: # state[2] == 'D'
  350. if (x <= state[3] and y <= state[4]):
  351. newMisioneriL = state[0] + x
  352. newKanibaliL = state[1] + y
  353. newMisioneriD = state[3] - x
  354. newKanibaliD = state[4] - y
  355.  
  356.  
  357. if (newMisioneriL == 0):
  358. if (newMisioneriD >= newKanibaliD):
  359. hashMap["M" + str(x) + "_" + str(y) + "K"] = (newMisioneriL,newKanibaliL,'L',newMisioneriD,newKanibaliD)
  360. elif (newMisioneriD == 0):
  361. if (newMisioneriL >= newKanibaliL):
  362. hashMap["M" + str(x) + "_" + str(y) + "K"] = (newMisioneriL,newKanibaliL,'L',newMisioneriD,newKanibaliD)
  363. elif (newMisioneriL >= newKanibaliL and newMisioneriD >= newKanibaliD):
  364. hashMap["M" + str(x) + "_" + str(y) + "K"] = (newMisioneriL,newKanibaliL,'L',newMisioneriD,newKanibaliD)
  365.  
  366. return hashMap
  367.  
  368. def actions(self, state):
  369. return self.successor(state).keys()
  370.  
  371. def result(self, state, action):
  372. possible = self.successor(state)
  373. return possible[action]
  374.  
  375. def h(self, node):
  376. return node.state[0] + node.state[1]
  377.  
  378. N = input()
  379. K = input()
  380.  
  381. problem = MisioneriKanibali((N,N,'L',0,0),K,None)
  382.  
  383. answer = astar_search(problem)
  384. print answer.solve()
  385. #Vasiot kod pisuvajte go pod ovoj komentar
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement