Advertisement
Guest User

Untitled

a guest
May 24th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.50 KB | None | 0 0
  1. import sys
  2. import bisect
  3.  
  4. """
  5. Опис на дефиницијата на состојбата
  6. Иницијалната состојба ми е претставена како tuple од tuples.
  7. Еден tuple е во форматот (x,y,z) каде што х претставува џ координатата на
  8. тенкот на таблата, у претставува у координата на таблата,а z претставува тежината на тенкот
  9. што му соодвестуваат координатите х и у. Полињата коишто немаат тенк не се означени. Ако z добие
  10. -1 тоа значи дека тој тенк не е дел од состојбата односно не се зема во предвид
  11.  
  12. Опис на функциите за транзиција од една во друга состојба
  13. Дефинирани се функциите pukajElement(a, intq) ,pukajDole(a, intq) ,pukajGore(a, intq) pukajLevo(a, intq)
  14. pukajDesno(a,intq) каде што а е една од tuples a intq e копија од state.
  15. Во pukajElement се намалува тежината на а односно z = z-1. Потоа во зависност на позицијата на а
  16. секој наблизок сосед по -x , x , y , -y (Gore , Dole , Levo, Desno ) оската исто така му се намалува z.
  17. Oваа нова состојба се запипшува во нов tuple којшто претставува новата состојба и се додава во речникот
  18. Овој процес се повторува за сите "jazili" a кој што се дел од state.
  19. """
  20.  
  21.  
  22.  
  23.  
  24. class Queue:
  25. """Queue is an abstract class/interface. There are three types:
  26. Stack(): A Last In First Out Queue.
  27. FIFOQueue(): A First In First Out Queue.
  28. PriorityQueue(order, f): Queue in sorted order (default min-first).
  29. Each type supports the following methods and functions:
  30. q.append(item) -- add an item to the queue
  31. q.extend(items) -- equivalent to: for item in items: q.append(item)
  32. q.pop() -- return the top item from the queue
  33. len(q) -- number of items in q (also q.__len())
  34. item in q -- does q contain item?
  35. Note that isinstance(Stack(), Queue) is false, because we implement stacks
  36. as lists. If Python ever gets interfaces, Queue will be an interface."""
  37.  
  38. def __init__(self):
  39. raise NotImplementedError
  40.  
  41. def extend(self, items):
  42. for item in items:
  43. self.append(item)
  44.  
  45. def Stack():
  46. """A Last-In-First-Out Queue."""
  47. return []
  48.  
  49. class FIFOQueue(Queue):
  50. """A First-In-First-Out Queue."""
  51.  
  52. def __init__(self):
  53. self.A = []
  54. self.start = 0
  55.  
  56. def append(self, item):
  57. self.A.append(item)
  58.  
  59. def __len__(self):
  60. return len(self.A) - self.start
  61.  
  62. def extend(self, items):
  63. self.A.extend(items)
  64.  
  65. def pop(self):
  66. e = self.A[self.start]
  67. self.start += 1
  68. if self.start > 5 and self.start > len(self.A) / 2:
  69. self.A = self.A[self.start:]
  70. self.start = 0
  71. return e
  72.  
  73. def __contains__(self, item):
  74. return item in self.A[self.start:]
  75.  
  76. class PriorityQueue(Queue):
  77. """A queue in which the minimum (or maximum) element (as determined by f and
  78. order) is returned first. If order is min, the item with minimum f(x) is
  79. returned first; if order is max, then it is the item with maximum f(x).
  80. Also supports dict-like lookup. This structure will be most useful in informed searches"""
  81.  
  82. def __init__(self, order=min, f=lambda x: x):
  83. self.A = []
  84. self.order = order
  85. self.f = f
  86.  
  87. def append(self, item):
  88. bisect.insort(self.A, (self.f(item), item))
  89.  
  90. def __len__(self):
  91. return len(self.A)
  92.  
  93. def pop(self):
  94. if self.order == min:
  95. return self.A.pop(0)[1]
  96. else:
  97. return self.A.pop()[1]
  98.  
  99. def __contains__(self, item):
  100. return any(item == pair[1] for pair in self.A)
  101.  
  102. def __getitem__(self, key):
  103. for _, item in self.A:
  104. if item == key:
  105. return item
  106.  
  107. def __delitem__(self, key):
  108. for i, (value, item) in enumerate(self.A):
  109. if item == key:
  110. self.A.pop(i)
  111.  
  112. class Node:
  113. """A node in a search tree. Contains a pointer to the parent (the node
  114. that this is a successor of) and to the actual state for this node. Note
  115. that if a state is arrived at by two paths, then there are two nodes with
  116. the same state. Also includes the action that got us to this state, and
  117. the total path_cost (also known as g) to reach the node. Other functions
  118. may add an f and h value; see best_first_graph_search and astar_search for
  119. an explanation of how the f and h values are handled. You will not need to
  120. subclass this class."""
  121.  
  122. def __init__(self, state, parent=None, action=None, path_cost=0):
  123. "Create a search tree Node, derived from a parent by an action."
  124. self.state = state
  125. self.parent = parent
  126. self.action = action
  127. self.path_cost = path_cost
  128. self.depth = 0
  129. if parent:
  130. self.depth = parent.depth + 1
  131.  
  132. def __repr__(self):
  133. return "<Node %s>" % (self.state,)
  134.  
  135. def __lt__(self, node):
  136. return self.state < node.state
  137.  
  138. def expand(self, problem):
  139. "List the nodes reachable in one step from this node."
  140. return [self.child_node(problem, action)
  141. for action in problem.actions(self.state)]
  142.  
  143. def child_node(self, problem, action):
  144. "Return a child node from this node"
  145. next = problem.result(self.state, action)
  146. return Node(next, self, action,
  147. problem.path_cost(self.path_cost, self.state,
  148. action, next))
  149.  
  150. def solution(self):
  151. "Return the sequence of actions to go from the root to this node."
  152. return [node.action for node in self.path()[1:]]
  153.  
  154. def solve(self):
  155. "Return the sequence of states to go from the root to this node."
  156. return [node.state for node in self.path()[0:]]
  157.  
  158. def path(self):
  159. "Return a list of nodes forming the path from the root to this node."
  160. x, result = self, []
  161. while x:
  162. result.append(x)
  163. x = x.parent
  164. return list(reversed(result))
  165.  
  166. # We want for a queue of nodes in breadth_first_search or
  167. # astar_search to have no duplicated states, so we treat nodes
  168. # with the same state as equal. [Problem: this may not be what you
  169. # want in other contexts.]
  170.  
  171. def __eq__(self, other):
  172. return isinstance(other, Node) and self.state == other.state
  173.  
  174. def __hash__(self):
  175. return hash(self.state)
  176.  
  177. class Problem:
  178. """The abstract class for a formal problem. You should subclass this and
  179. implement the method successor, and possibly __init__, goal_test, and
  180. path_cost. Then you will create instances of your subclass and solve them
  181. with the various search functions."""
  182.  
  183. def __init__(self, initial, goal=None):
  184. """The constructor specifies the initial state, and possibly a goal
  185. state, if there is a unique goal. Your subclass's constructor can add
  186. other arguments."""
  187. self.initial = initial
  188. self.goal = goal
  189.  
  190. def successor(self, state):
  191. """Given a state, return a dictionary of {action : state} pairs reachable
  192. from this state. If there are many successors, consider an iterator
  193. that yields the successors one at a time, rather than building them
  194. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  195. raise NotImplementedError
  196.  
  197. def actions(self, state):
  198. """Given a state, return a list of all actions possible from that state"""
  199. raise NotImplementedError
  200.  
  201. def result(self, state, action):
  202. """Given a state and action, return the resulting state"""
  203. raise NotImplementedError
  204.  
  205. def goal_test(self, state):
  206. """Return True if the state is a goal. The default method compares the
  207. state to self.goal, as specified in the constructor. Implement this
  208. method if checking against a single self.goal is not enough."""
  209. return state == self.goal
  210.  
  211. def path_cost(self, c, state1, action, state2):
  212. """Return the cost of a solution path that arrives at state2 from
  213. state1 via action, assuming cost c to get up to state1. If the problem
  214. is such that the path doesn't matter, this function will only look at
  215. state2. If the path does matter, it will consider c and maybe state1
  216. and action. The default method costs 1 for every step in the path."""
  217. return c + 1
  218.  
  219. def value(self):
  220. """For optimization problems, each state has a value. Hill-climbing
  221. and related algorithms try to maximize this value."""
  222. raise NotImplementedError
  223.  
  224. def tree_search(problem, fringe):
  225. """Search through the successors of a problem to find a goal.
  226. The argument fringe should be an empty queue."""
  227. fringe.append(Node(problem.initial))
  228. while fringe:
  229. node = fringe.pop()
  230. # print(node.state)
  231. if problem.goal_test(node.state):
  232. return node
  233. fringe.extend(node.expand(problem))
  234. return None
  235. def breadth_first_tree_search(problem):
  236. "Search the shallowest nodes in the search tree first."
  237. return tree_search(problem, FIFOQueue())
  238.  
  239. def proverka(tmp,lista):
  240. for a in lista:
  241. if a.__eq__(tmp) and a[2] != -1:
  242. return True
  243. return False
  244.  
  245. def pukajElement(tmp, lista):
  246. for a in lista:
  247. if a.__eq__(tmp) and a[2] != -1:
  248. x = lista.index(a)
  249. tup = (a[0], a[1], a[2] - 1)
  250. tmplista = lista[:x] + (tup,) + lista[x + 1:]
  251. # print(tmplista)
  252. lista = tmplista
  253. return lista
  254.  
  255.  
  256. def pukajDesno(tmp, lista):
  257. razlika = 50
  258. flag = False
  259. for a in lista:
  260. neisti = a.__ne__(tmp)
  261. if a[0] == tmp[0] and a[2] != -1 and neisti and tmp[1] < a[1]:
  262. if razlika > (a[1] - tmp[1]):
  263. razlika = tmp[1] - a[1]
  264. element = a
  265. flag = True
  266. # print("elementot e ")
  267. # print(element)
  268. if flag:
  269. for a in lista:
  270. isti = a.__eq__(element)
  271. if isti:
  272. x = lista.index(a)
  273. tup = (a[0], a[1], a[2] - 1)
  274. tmplista = lista[:x] + (tup,) + lista[x + 1:]
  275. # print(tmplista)
  276. lista = tmplista
  277. return lista
  278. else:
  279. #print("FLAZI22222222")
  280. return lista
  281.  
  282.  
  283. def pukajLevo(tmp, lista):
  284. razlika = 50
  285. flag = False
  286. for a in lista:
  287. neisti = a.__ne__(tmp)
  288. if a[0] == tmp[0] and a[2] != -1 and neisti and tmp[1] > a[1]:
  289. if razlika > (tmp[1] - a[1]):
  290. razlika = tmp[1] - a[1]
  291. element = a
  292. flag = True
  293. if flag:
  294. for a in lista:
  295. isti = a.__eq__(element)
  296. if isti:
  297. x = lista.index(a)
  298. tup = (a[0], a[1], a[2] - 1)
  299. tmplista = lista[:x] + (tup,) + lista[x + 1:]
  300. # print(tmplista)
  301. lista = tmplista
  302. return lista
  303. else:
  304. # print("FLAZI22222222")
  305. return lista
  306.  
  307.  
  308. def pukajGore(tmp, lista):
  309. razlika = 50
  310. flag = False
  311. for a in lista:
  312. neisti = a.__ne__(tmp)
  313. if a[1] == tmp[1] and a[2] != -1 and neisti and tmp[0] > a[0]:
  314. if razlika > (tmp[0] - a[0]):
  315. razlika = tmp[0] - a[0]
  316. element = a
  317. flag = True
  318. # print("elementot e ")
  319. # print(element)
  320. if flag:
  321. for a in lista:
  322. isti = a.__eq__(element)
  323. if isti:
  324. x = lista.index(a)
  325. tup = (a[0], a[1], a[2] - 1)
  326. tmplista = lista[:x] + (tup,) + lista[x + 1:]
  327. # print(tmplista)
  328. lista = tmplista
  329. return lista
  330. else:
  331. #print("FLAZI22222222")
  332. return lista
  333.  
  334.  
  335. def pukajDole(tmp,lista):
  336. razlika = 50
  337. flag = False
  338. for a in lista:
  339. neisti = a.__ne__(tmp)
  340. if a[1] == tmp[1] and a[2] != -1 and neisti and tmp[0] < a[0]:
  341. if razlika > (a[0] - tmp[0]):
  342. razlika = a[0] - tmp[0]
  343. element = a
  344. flag = True
  345. # print("elementot e ")
  346. # print(element)
  347. if flag:
  348. for a in lista:
  349. isti = a.__eq__(element)
  350. if isti:
  351. x = lista.index(a)
  352. tup = (a[0], a[1], a[2] - 1)
  353. tmplista = lista[:x] + (tup,) + lista[x + 1:]
  354. # print(tmplista)
  355. lista = tmplista
  356. return lista
  357. else:
  358. # print("FLAZI22222222")
  359. return lista
  360.  
  361. class WJ(Problem):
  362.  
  363. def __init__(self,initial=((0, 2, 1), (1, 0, 0), (1, 2, 1), (1, 3, 0), (2, 2, 1), (3, 1, 2), (3, 3, 0)), goal = ((0, 2, -1), (1, 0,-1), (1, 2, -1), (1, 3, -1), (2, 2, -1), (3, 1, -1), (3, 3, -1))):
  364. self.initial = initial
  365. self.goal = goal
  366.  
  367. def goal_test(self, state):
  368. """ Vraka true ako sostojbata e celna """
  369. g = self.goal
  370. return g.__eq__(state)
  371.  
  372. def successor(self, state):
  373. successors = dict()
  374. x = 0
  375. for a in state:
  376. intq = state[:]
  377. if proverka(a, intq):
  378. intq = pukajElement(a, intq)
  379. intq = pukajDole(a, intq)
  380. intq = pukajGore(a, intq)
  381. intq = pukajLevo(a, intq)
  382. intq = pukajDesno(a, intq)
  383. successors[x] = intq
  384. x += 1
  385. return successors
  386.  
  387. def actions(self, state):
  388. #print(self.successor(state).keys())
  389. return self.successor(state).keys()
  390.  
  391. def result(self, state, action):
  392. possible = self.successor(state)
  393. return possible[action]
  394.  
  395.  
  396. WJInstance = WJ()
  397. print(WJInstance)
  398. answer1 = breadth_first_tree_search(WJInstance)
  399. print(answer1.solution)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement