Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.97 KB | None | 0 0
  1. #podvizni prepreki
  2.  
  3. class Queue:
  4. """Queue is an abstract class/interface. There are three types:
  5. Stack(): A Last In First Out Queue.
  6. FIFOQueue(): A First In First Out Queue.
  7. PriorityQueue(order, f): Queue in sorted order (default min-first).
  8. Each type supports the following methods and functions:
  9. q.append(item) -- add an item to the queue
  10. q.extend(items) -- equivalent to: for item in items: q.append(item)
  11. q.pop() -- return the top item from the queue
  12. len(q) -- number of items in q (also q.__len())
  13. item in q -- does q contain item?
  14. Note that isinstance(Stack(), Queue) is false, because we implement stacks
  15. as lists. If Python ever gets interfaces, Queue will be an interface."""
  16.  
  17. def __init__(self):
  18. raise NotImplementedError
  19.  
  20. def extend(self, items):
  21. for item in items:
  22. self.append(item)
  23.  
  24.  
  25. def Stack():
  26. """A Last-In-First-Out Queue."""
  27. return []
  28.  
  29.  
  30. class FIFOQueue(Queue):
  31. """A First-In-First-Out Queue."""
  32.  
  33. def __init__(self):
  34. self.A = []
  35. self.start = 0
  36.  
  37. def append(self, item):
  38. self.A.append(item)
  39.  
  40. def __len__(self):
  41. return len(self.A) - self.start
  42.  
  43. def extend(self, items):
  44. self.A.extend(items)
  45.  
  46. def pop(self):
  47. e = self.A[self.start]
  48. self.start += 1
  49. if self.start > 5 and self.start > len(self.A) / 2:
  50. self.A = self.A[self.start:]
  51. self.start = 0
  52. return e
  53.  
  54. def __contains__(self, item):
  55. return item in self.A[self.start:]
  56.  
  57.  
  58. class PriorityQueue(Queue):
  59. """A queue in which the minimum (or maximum) element (as determined by f and
  60. order) is returned first. If order is min, the item with minimum f(x) is
  61. returned first; if order is max, then it is the item with maximum f(x).
  62. Also supports dict-like lookup. This structure will be most useful in informed searches"""
  63.  
  64. def __init__(self, order=min, f=lambda x: x):
  65. self.A = []
  66. self.order = order
  67. self.f = f
  68.  
  69. def append(self, item):
  70. bisect.insort(self.A, (self.f(item), item))
  71.  
  72. def __len__(self):
  73. return len(self.A)
  74.  
  75. def pop(self):
  76. if self.order == min:
  77. return self.A.pop(0)[1]
  78. else:
  79. return self.A.pop()[1]
  80.  
  81. def __contains__(self, item):
  82. return any(item == pair[1] for pair in self.A)
  83.  
  84. def __getitem__(self, key):
  85. for _, item in self.A:
  86. if item == key:
  87. return item
  88.  
  89. def __delitem__(self, key):
  90. for i, (value, item) in enumerate(self.A):
  91. if item == key:
  92. self.A.pop(i)
  93.  
  94.  
  95. # ______________________________________________________________________________________________
  96. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  97. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  98. # na sekoj eden problem sto sakame da go resime
  99.  
  100.  
  101. class Problem:
  102. """The abstract class for a formal problem. You should subclass this and
  103. implement the method successor, and possibly __init__, goal_test, and
  104. path_cost. Then you will create instances of your subclass and solve them
  105. with the various search functions."""
  106.  
  107. def __init__(self, initial, goal=None):
  108. """The constructor specifies the initial state, and possibly a goal
  109. state, if there is a unique goal. Your subclass's constructor can add
  110. other arguments."""
  111. self.initial = initial
  112. self.goal = goal
  113.  
  114. def successor(self, state):
  115. """Given a state, return a dictionary of {action : state} pairs reachable
  116. from this state. If there are many successors, consider an iterator
  117. that yields the successors one at a time, rather than building them
  118. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  119. raise NotImplementedError
  120.  
  121. def actions(self, state):
  122. """Given a state, return a list of all actions possible from that state"""
  123. raise NotImplementedError
  124.  
  125. def result(self, state, action):
  126. """Given a state and action, return the resulting state"""
  127. raise NotImplementedError
  128.  
  129. def goal_test(self, state):
  130. """Return True if the state is a goal. The default method compares the
  131. state to self.goal, as specified in the constructor. Implement this
  132. method if checking against a single self.goal is not enough."""
  133. return state == self.goal
  134.  
  135. def path_cost(self, c, state1, action, state2):
  136. """Return the cost of a solution path that arrives at state2 from
  137. state1 via action, assuming cost c to get up to state1. If the problem
  138. is such that the path doesn't matter, this function will only look at
  139. state2. If the path does matter, it will consider c and maybe state1
  140. and action. The default method costs 1 for every step in the path."""
  141. return c + 1
  142.  
  143. def value(self):
  144. """For optimization problems, each state has a value. Hill-climbing
  145. and related algorithms try to maximize this value."""
  146. raise NotImplementedError
  147.  
  148.  
  149. # ______________________________________________________________________________
  150. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  151. # Klasata Node ne se nasleduva
  152.  
  153. class Node:
  154. """A node in a search tree. Contains a pointer to the parent (the node
  155. that this is a successor of) and to the actual state for this node. Note
  156. that if a state is arrived at by two paths, then there are two nodes with
  157. the same state. Also includes the action that got us to this state, and
  158. the total path_cost (also known as g) to reach the node. Other functions
  159. may add an f and h value; see best_first_graph_search and astar_search for
  160. an explanation of how the f and h values are handled. You will not need to
  161. subclass this class."""
  162.  
  163. def __init__(self, state, parent=None, action=None, path_cost=0):
  164. "Create a search tree Node, derived from a parent by an action."
  165. self.state = state
  166. self.parent = parent
  167. self.action = action
  168. self.path_cost = path_cost
  169. self.depth = 0
  170. if parent:
  171. self.depth = parent.depth + 1
  172.  
  173. def __repr__(self):
  174. return "<Node %s>" % (self.state,)
  175.  
  176. def __lt__(self, node):
  177. return self.state < node.state
  178.  
  179. def expand(self, problem):
  180. "List the nodes reachable in one step from this node."
  181. return [self.child_node(problem, action)
  182. for action in problem.actions(self.state)]
  183.  
  184. def child_node(self, problem, action):
  185. "Return a child node from this node"
  186. next = problem.result(self.state, action)
  187. return Node(next, self, action,
  188. problem.path_cost(self.path_cost, self.state,
  189. action, next))
  190.  
  191. def solution(self):
  192. "Return the sequence of actions to go from the root to this node."
  193. return [node.action for node in self.path()[1:]]
  194.  
  195. def solve(self):
  196. "Return the sequence of states to go from the root to this node."
  197. return [node.state for node in self.path()[0:]]
  198.  
  199. def path(self):
  200. "Return a list of nodes forming the path from the root to this node."
  201. x, result = self, []
  202. while x:
  203. result.append(x)
  204. x = x.parent
  205. return list(reversed(result))
  206.  
  207. # We want for a queue of nodes in breadth_first_search or
  208. # astar_search to have no duplicated states, so we treat nodes
  209. # with the same state as equal. [Problem: this may not be what you
  210. # want in other contexts.]
  211.  
  212. def __eq__(self, other):
  213. return isinstance(other, Node) and self.state == other.state
  214.  
  215. def __hash__(self):
  216. return hash(self.state)
  217.  
  218.  
  219. # ________________________________________________________________________________________________________
  220. # Neinformirano prebaruvanje vo ramki na drvo
  221. # Vo ramki na drvoto ne razresuvame jamki
  222.  
  223. def tree_search(problem, fringe):
  224. """Search through the successors of a problem to find a goal.
  225. The argument fringe should be an empty queue."""
  226. fringe.append(Node(problem.initial))
  227. while fringe:
  228. node = fringe.pop()
  229. print(node.state)
  230. if problem.goal_test(node.state):
  231. return node
  232. fringe.extend(node.expand(problem))
  233. return None
  234.  
  235.  
  236. def breadth_first_tree_search(problem):
  237. "Search the shallowest nodes in the search tree first."
  238. return tree_search(problem, FIFOQueue())
  239.  
  240.  
  241. def depth_first_tree_search(problem):
  242. "Search the deepest nodes in the search tree first."
  243. return tree_search(problem, Stack())
  244.  
  245.  
  246. # ________________________________________________________________________________________________________
  247. # Neinformirano prebaruvanje vo ramki na graf
  248. # Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  249.  
  250. def graph_search(problem, fringe):
  251. """Search through the successors of a problem to find a goal.
  252. The argument fringe should be an empty queue.
  253. If two paths reach a state, only use the best one."""
  254. closed = {}
  255. fringe.append(Node(problem.initial))
  256. while fringe:
  257. node = fringe.pop()
  258. if problem.goal_test(node.state):
  259. return node
  260. if node.state not in closed:
  261. closed[node.state] = True
  262. fringe.extend(node.expand(problem))
  263. return None
  264.  
  265.  
  266. def breadth_first_graph_search(problem):
  267. "Search the shallowest nodes in the search tree first."
  268. return graph_search(problem, FIFOQueue())
  269.  
  270.  
  271. def depth_first_graph_search(problem):
  272. "Search the deepest nodes in the search tree first."
  273. return graph_search(problem, Stack())
  274.  
  275.  
  276. def uniform_cost_search(problem):
  277. "Search the nodes in the search tree with lowest cost first."
  278. return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  279.  
  280.  
  281. def depth_limited_search(problem, limit=50):
  282. "depth first search with limited depth"
  283.  
  284. def recursive_dls(node, problem, limit):
  285. "helper function for depth limited"
  286. cutoff_occurred = False
  287. if problem.goal_test(node.state):
  288. return node
  289. elif node.depth == limit:
  290. return 'cutoff'
  291. else:
  292. for successor in node.expand(problem):
  293. result = recursive_dls(successor, problem, limit)
  294. if result == 'cutoff':
  295. cutoff_occurred = True
  296. elif result != None:
  297. return result
  298. if cutoff_occurred:
  299. return 'cutoff'
  300. else:
  301. return None
  302.  
  303. # Body of depth_limited_search:
  304. return recursive_dls(Node(problem.initial), problem, limit)
  305.  
  306.  
  307. def iterative_deepening_search(problem):
  308. for depth in xrange(sys.maxint):
  309. result = depth_limited_search(problem, depth)
  310. if result is not 'cutoff':
  311. return result
  312.  
  313.  
  314. # _________________________________________________________________________________________________________
  315. # PRIMER 1 : PROBLEM SO DVA SADA SO VODA
  316. # OPIS: Dadeni se dva sada J0 i J1 so kapaciteti C0 i C1
  317. # Na pocetok dvata sada se polni. Inicijalnata sostojba moze da se prosledi na pocetok
  318. # Problemot e kako da se stigne do sostojba vo koja J0 ke ima G0 litri, a J1 ke ima G1 litri
  319. # AKCII: 1. Da se isprazni bilo koj od sadovite
  320. # 2. Da se prefrli tecnosta od eden sad vo drug so toa sto ne moze da se nadmine kapacitetot na sadovite
  321. # Moze da ima i opcionalen tret vid na akcii 3. Napolni bilo koj od sadovite (studentite da ja implementiraat ovaa varijanta)
  322. # ________________________________________________________________________________________________________
  323.  
  324. class WJ(Problem):
  325. """STATE: Torka od oblik (3,2) if jug J0 has 3 liters and J1 2 liters
  326. Opcionalno moze za nekoj od sadovite da se sretne i vrednost '*' sto znaci deka e nebitno kolku ima vo toj sad
  327. GOAL: Predefinirana sostojba do kade sakame da stigneme. Ako ne interesira samo eden sad za drugiot mozeme da stavime '*'
  328. PROBLEM: Se specificiraat kapacitetite na sadovite, pocetna sostojba i cel """
  329.  
  330. def __init__(self, capacities=(5, 2), initial=(5, 0), goal=(0, 1)):
  331. self.capacities = capacities
  332. self.initial = initial
  333. self.goal = goal
  334.  
  335. def goal_test(self, state):
  336. """ Vraka true ako sostojbata e celna """
  337. g = self.goal
  338. return (state[0] == g[0] or g[0] == '*') and \
  339. (state[1] == g[1] or g[1] == '*')
  340.  
  341. def successor(self, J):
  342. """Vraka recnik od sledbenici na sostojbata"""
  343. successors = dict()
  344. J0, J1 = J
  345. (C0, C1) = self.capacities
  346. if J0 > 0:
  347. Jnew = 0, J1
  348. successors['dump jug 0'] = Jnew
  349. if J1 > 0:
  350. Jnew = J0, 0
  351. successors['dump jug 1'] = Jnew
  352. if J1 < C1 and J0 > 0:
  353. delta = min(J0, C1 - J1)
  354. Jnew = J0 - delta, J1 + delta
  355. successors['pour jug 0 into jug 1'] = Jnew
  356. if J0 < C0 and J1 > 0:
  357. delta = min(J1, C0 - J0)
  358. Jnew = J0 + delta, J1 - delta
  359. successors['pour jug 1 into jug 0'] = Jnew
  360. return successors
  361.  
  362. def actions(self, state):
  363. return self.successor(state).keys()
  364.  
  365. def result(self, state, action):
  366. possible = self.successor(state)
  367. return possible[action]
  368.  
  369.  
  370. # So vaka definiraniot problem mozeme da gi koristime site neinformirani prebaruvanja
  371. # Vo prodolzenie se dadeni mozni povici (vnimavajte za da moze da napravite povik mora da definirate problem)
  372. #
  373. # WJInstance = WJ((5, 2), (5, 2), ('*', 1))
  374. # print WJInstance
  375. #
  376. # answer1 = breadth_first_tree_search(WJInstance)
  377. # print answer1.solve()
  378. #
  379. # answer2 = depth_first_tree_search(WJInstance) #vnimavajte na ovoj povik, moze da vleze vo beskonecna jamka
  380. # print answer2.solve()
  381. #
  382. # answer3 = breadth_first_graph_search(WJInstance)
  383. # print answer3.solve()
  384. #
  385. # answer4 = depth_first_graph_search(WJInstance)
  386. # print answer4.solve()
  387. #
  388. # answer5 = depth_limited_search(WJInstance)
  389. # print answer5.solve()
  390. #
  391. # answer6 = iterative_deepening_search(WJInstance)
  392. # print answer6.solve()
  393. class CrnoBelo(Problem):
  394. def __init__(self, initial, goal):
  395. self.initial = str(initial)
  396. self.goal = str(goal)
  397.  
  398. def goal_test(self, state):
  399. return state == self.goal
  400.  
  401. def successor(self, state):
  402. successors = dict()
  403. dx = [-1, 0, 1, 0]
  404. dy = [0, 1, 0, -1]
  405. for x in range(0, N):
  406. for y in range(0, N):
  407. Matrix = eval(state)
  408. if Matrix[x][y] == 1:
  409. Matrix[x][y] = 0
  410. for k in range(4):
  411. newX = x + dx[k]
  412. newY = y + dy[k]
  413. if newX >= 0 and newX < N and newY >= 0 and newY < N:
  414. Matrix[newX][newY] = (Matrix[newX][newY] + 1) % 2
  415. stateNew = Matrix
  416. akcija = "X:" + str(x) + "Y:" + str(y)
  417. successors[akcija] = str(stateNew)
  418.  
  419. return successors
  420.  
  421. def actions(self, state):
  422. return self.successor(state).keys()
  423.  
  424. def result(self, state, action):
  425. possible = self.successor(state)
  426. return possible[action]
  427.  
  428.  
  429. N = int(input())
  430. polinja = map(int, input().split(','))
  431. polinjaList = list(polinja)
  432. InitialMatrix = [[0 for x in range(N)] for y in range(N)]
  433. for i in range(0, N):
  434. for j in range(0, N):
  435. InitialMatrix[i][j] = polinjaList[i * N + j]
  436. GoalMatrix = [[0 for x in range(N)] for y in range(N)]
  437.  
  438. crnoBeloinstance = CrnoBelo(InitialMatrix, GoalMatrix)
  439. answer = breadth_first_graph_search(crnoBeloinstance).solution()
  440. print(answer)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement