Advertisement
Guest User

Germanija

a guest
May 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.98 KB | None | 0 0
  1. # Python modul vo koj se implementirani algoritmite za neinformirano i informirano prebaruvanje
  2.  
  3. # ______________________________________________________________________________________________
  4. # Improtiranje na dopolnitelno potrebni paketi za funkcioniranje na kodovite
  5.  
  6. import sys
  7. import bisect
  8.  
  9. infinity = float('inf') # sistemski definirana vrednost za beskonecnost
  10.  
  11.  
  12. # ______________________________________________________________________________________________
  13. # Definiranje na pomosni strukturi za cuvanje na listata na generirani, no neprovereni jazli
  14.  
  15. class Queue:
  16. """Queue is an abstract class/interface. There are three types:
  17. Stack(): A Last In First Out Queue.
  18. FIFOQueue(): A First In First Out Queue.
  19. PriorityQueue(order, f): Queue in sorted order (default min-first).
  20. Each type supports the following methods and functions:
  21. q.append(item) -- add an item to the queue
  22. q.extend(items) -- equivalent to: for item in items: q.append(item)
  23. q.pop() -- return the top item from the queue
  24. len(q) -- number of items in q (also q.__len())
  25. item in q -- does q contain item?
  26. Note that isinstance(Stack(), Queue) is false, because we implement stacks
  27. as lists. If Python ever gets interfaces, Queue will be an interface."""
  28.  
  29. def __init__(self):
  30. raise NotImplementedError
  31.  
  32. def extend(self, items):
  33. for item in items:
  34. self.append(item)
  35.  
  36.  
  37. def Stack():
  38. """A Last-In-First-Out Queue."""
  39. return []
  40.  
  41.  
  42. class FIFOQueue(Queue):
  43. """A First-In-First-Out Queue."""
  44.  
  45. def __init__(self):
  46. self.A = []
  47. self.start = 0
  48.  
  49. def append(self, item):
  50. self.A.append(item)
  51.  
  52. def __len__(self):
  53. return len(self.A) - self.start
  54.  
  55. def extend(self, items):
  56. self.A.extend(items)
  57.  
  58. def pop(self):
  59. e = self.A[self.start]
  60. self.start += 1
  61. if self.start > 5 and self.start > len(self.A) / 2:
  62. self.A = self.A[self.start:]
  63. self.start = 0
  64. return e
  65.  
  66. def __contains__(self, item):
  67. return item in self.A[self.start:]
  68.  
  69.  
  70. class PriorityQueue(Queue):
  71. """A queue in which the minimum (or maximum) element (as determined by f and
  72. order) is returned first. If order is min, the item with minimum f(x) is
  73. returned first; if order is max, then it is the item with maximum f(x).
  74. Also supports dict-like lookup. This structure will be most useful in informed searches"""
  75.  
  76. def __init__(self, order=min, f=lambda x: x):
  77. self.A = []
  78. self.order = order
  79. self.f = f
  80.  
  81. def append(self, item):
  82. bisect.insort(self.A, (self.f(item), item))
  83.  
  84. def __len__(self):
  85. return len(self.A)
  86.  
  87. def pop(self):
  88. if self.order == min:
  89. return self.A.pop(0)[1]
  90. else:
  91. return self.A.pop()[1]
  92.  
  93. def __contains__(self, item):
  94. return any(item == pair[1] for pair in self.A)
  95.  
  96. def __getitem__(self, key):
  97. for _, item in self.A:
  98. if item == key:
  99. return item
  100.  
  101. def __delitem__(self, key):
  102. for i, (value, item) in enumerate(self.A):
  103. if item == key:
  104. self.A.pop(i)
  105.  
  106.  
  107. # ______________________________________________________________________________________________
  108. # Definiranje na klasa za strukturata na problemot koj ke go resavame so prebaruvanje
  109. # Klasata Problem e apstraktna klasa od koja pravime nasleduvanje za definiranje na osnovnite karakteristiki
  110. # na sekoj eden problem sto sakame da go resime
  111.  
  112.  
  113. class Problem:
  114. """The abstract class for a formal problem. You should subclass this and
  115. implement the method successor, and possibly __init__, goal_test, and
  116. path_cost. Then you will create instances of your subclass and solve them
  117. with the various search functions."""
  118.  
  119. def __init__(self, initial, goal=None):
  120. """The constructor specifies the initial state, and possibly a goal
  121. state, if there is a unique goal. Your subclass's constructor can add
  122. other arguments."""
  123. self.initial = initial
  124. self.goal = goal
  125.  
  126. def successor(self, state):
  127. """Given a state, return a dictionary of {action : state} pairs reachable
  128. from this state. If there are many successors, consider an iterator
  129. that yields the successors one at a time, rather than building them
  130. all at once. Iterators will work fine within the framework. Yielding is not supported in Python 2.7"""
  131. raise NotImplementedError
  132.  
  133. def actions(self, state):
  134. """Given a state, return a list of all actions possible from that state"""
  135. raise NotImplementedError
  136.  
  137. def result(self, state, action):
  138. """Given a state and action, return the resulting state"""
  139. raise NotImplementedError
  140.  
  141. def goal_test(self, state):
  142. """Return True if the state is a goal. The default method compares the
  143. state to self.goal, as specified in the constructor. Implement this
  144. method if checking against a single self.goal is not enough."""
  145. return state == self.goal
  146.  
  147. def path_cost(self, c, state1, action, state2):
  148. """Return the cost of a solution path that arrives at state2 from
  149. state1 via action, assuming cost c to get up to state1. If the problem
  150. is such that the path doesn't matter, this function will only look at
  151. state2. If the path does matter, it will consider c and maybe state1
  152. and action. The default method costs 1 for every step in the path."""
  153. return c + 1
  154.  
  155. def value(self):
  156. """For optimization problems, each state has a value. Hill-climbing
  157. and related algorithms try to maximize this value."""
  158. raise NotImplementedError
  159.  
  160.  
  161. # ______________________________________________________________________________
  162. # Definiranje na klasa za strukturata na jazel od prebaruvanje
  163. # Klasata Node ne se nasleduva
  164.  
  165. class Node:
  166. """A node in a search tree. Contains a pointer to the parent (the node
  167. that this is a successor of) and to the actual state for this node. Note
  168. that if a state is arrived at by two paths, then there are two nodes with
  169. the same state. Also includes the action that got us to this state, and
  170. the total path_cost (also known as g) to reach the node. Other functions
  171. may add an f and h value; see best_first_graph_search and astar_search for
  172. an explanation of how the f and h values are handled. You will not need to
  173. subclass this class."""
  174.  
  175. def __init__(self, state, parent=None, action=None, path_cost=0):
  176. "Create a search tree Node, derived from a parent by an action."
  177. self.state = state
  178. self.parent = parent
  179. self.action = action
  180. self.path_cost = path_cost
  181. self.depth = 0
  182. if parent:
  183. self.depth = parent.depth + 1
  184.  
  185. def __repr__(self):
  186. return "<Node %s>" % (self.state,)
  187.  
  188. def __lt__(self, node):
  189. return self.state < node.state
  190.  
  191. def expand(self, problem):
  192. "List the nodes reachable in one step from this node."
  193. return [self.child_node(problem, action)
  194. for action in problem.actions(self.state)]
  195.  
  196. def child_node(self, problem, action):
  197. "Return a child node from this node"
  198. next = problem.result(self.state, action)
  199. return Node(next, self, action,
  200. problem.path_cost(self.path_cost, self.state,
  201. action, next))
  202.  
  203. def solution(self):
  204. "Return the sequence of actions to go from the root to this node."
  205. return [node.action for node in self.path()[1:]]
  206.  
  207. def solve(self):
  208. "Return the sequence of states to go from the root to this node."
  209. return [node.state for node in self.path()[0:]]
  210.  
  211. def path(self):
  212. "Return a list of nodes forming the path from the root to this node."
  213. x, result = self, []
  214. while x:
  215. result.append(x)
  216. x = x.parent
  217. return list(reversed(result))
  218.  
  219. # We want for a queue of nodes in breadth_first_search or
  220. # astar_search to have no duplicated states, so we treat nodes
  221. # with the same state as equal. [Problem: this may not be what you
  222. # want in other contexts.]
  223.  
  224. def __eq__(self, other):
  225. return isinstance(other, Node) and self.state == other.state
  226.  
  227. def __hash__(self):
  228. return hash(self.state)
  229.  
  230.  
  231. # ________________________________________________________________________________________________________
  232. # Neinformirano prebaruvanje vo ramki na drvo
  233. # Vo ramki na drvoto ne razresuvame jamki
  234.  
  235. def tree_search(problem, fringe):
  236. """Search through the successors of a problem to find a goal.
  237. The argument fringe should be an empty queue."""
  238. fringe.append(Node(problem.initial))
  239. while fringe:
  240. node = fringe.pop()
  241.  
  242. if problem.goal_test(node.state):
  243. return node
  244. fringe.extend(node.expand(problem))
  245. return None
  246.  
  247.  
  248. def breadth_first_tree_search(problem):
  249. "Search the shallowest nodes in the search tree first."
  250. return tree_search(problem, FIFOQueue())
  251.  
  252.  
  253. def depth_first_tree_search(problem):
  254. "Search the deepest nodes in the search tree first."
  255. return tree_search(problem, Stack())
  256.  
  257.  
  258. # ________________________________________________________________________________________________________
  259. # Neinformirano prebaruvanje vo ramki na graf
  260. # Osnovnata razlika e vo toa sto ovde ne dozvoluvame jamki t.e. povtoruvanje na sostojbi
  261.  
  262. def graph_search(problem, fringe):
  263. """Search through the successors of a problem to find a goal.
  264. The argument fringe should be an empty queue.
  265. If two paths reach a state, only use the best one."""
  266. closed = {}
  267. fringe.append(Node(problem.initial))
  268. while fringe:
  269. node = fringe.pop()
  270. if problem.goal_test(node.state):
  271. return node
  272. if node.state not in closed:
  273. closed[node.state] = True
  274. fringe.extend(node.expand(problem))
  275. return None
  276.  
  277.  
  278. def breadth_first_graph_search(problem):
  279. "Search the shallowest nodes in the search tree first."
  280. return graph_search(problem, FIFOQueue())
  281.  
  282.  
  283. def depth_first_graph_search(problem):
  284. "Search the deepest nodes in the search tree first."
  285. return graph_search(problem, Stack())
  286.  
  287.  
  288. def uniform_cost_search(problem):
  289. "Search the nodes in the search tree with lowest cost first."
  290. return graph_search(problem, PriorityQueue(lambda a, b: a.path_cost < b.path_cost))
  291.  
  292.  
  293. def depth_limited_search(problem, limit=50):
  294. "depth first search with limited depth"
  295.  
  296. def recursive_dls(node, problem, limit):
  297. "helper function for depth limited"
  298. cutoff_occurred = False
  299. if problem.goal_test(node.state):
  300. return node
  301. elif node.depth == limit:
  302. return 'cutoff'
  303. else:
  304. for successor in node.expand(problem):
  305. result = recursive_dls(successor, problem, limit)
  306. if result == 'cutoff':
  307. cutoff_occurred = True
  308. elif result != None:
  309. return result
  310. if cutoff_occurred:
  311. return 'cutoff'
  312. else:
  313. return None
  314.  
  315. # Body of depth_limited_search:
  316. return recursive_dls(Node(problem.initial), problem, limit)
  317.  
  318.  
  319. def iterative_deepening_search(problem):
  320. for depth in range(sys.maxint):
  321. result = depth_limited_search(problem, depth)
  322. if result is not 'cutoff':
  323. return result
  324.  
  325.  
  326. # ________________________________________________________________________________________________________
  327. # Pomosna funkcija za informirani prebaruvanja
  328. # So pomos na ovaa funkcija gi keshirame rezultatite od funkcijata na evaluacija
  329.  
  330. def memoize(fn, slot=None):
  331. """Memoize fn: make it remember the computed value for any argument list.
  332. If slot is specified, store result in that slot of first argument.
  333. If slot is false, store results in a dictionary."""
  334. if slot:
  335. def memoized_fn(obj, *args):
  336. if hasattr(obj, slot):
  337. return getattr(obj, slot)
  338. else:
  339. val = fn(obj, *args)
  340. setattr(obj, slot, val)
  341. return val
  342. else:
  343. def memoized_fn(*args):
  344. if not memoized_fn.cache.has_key(args):
  345. memoized_fn.cache[args] = fn(*args)
  346. return memoized_fn.cache[args]
  347.  
  348. memoized_fn.cache = {}
  349. return memoized_fn
  350.  
  351.  
  352. # ________________________________________________________________________________________________________
  353. # Informirano prebaruvanje vo ramki na graf
  354.  
  355. def best_first_graph_search(problem, f):
  356. """Search the nodes with the lowest f scores first.
  357. You specify the function f(node) that you want to minimize; for example,
  358. if f is a heuristic estimate to the goal, then we have greedy best
  359. first search; if f is node.depth then we have breadth-first search.
  360. There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  361. values will be cached on the nodes as they are computed. So after doing
  362. a best first search you can examine the f values of the path returned."""
  363.  
  364. f = memoize(f, 'f')
  365. node = Node(problem.initial)
  366. if problem.goal_test(node.state):
  367. return node
  368. frontier = PriorityQueue(min, f)
  369. frontier.append(node)
  370. explored = set()
  371. while frontier:
  372. node = frontier.pop()
  373. if problem.goal_test(node.state):
  374. return node
  375. # print("Popped: " + node.state)
  376. explored.add(node.state)
  377. for child in node.expand(problem):
  378. if child.state not in explored and child not in frontier:
  379. frontier.append(child)
  380. # print("Child added: " + child.state)
  381. elif child in frontier:
  382. incumbent = frontier[child]
  383. if f(child) < f(incumbent):
  384. del frontier[incumbent]
  385. frontier.append(child)
  386. return None
  387.  
  388.  
  389. def greedy_best_first_graph_search(problem, h=None):
  390. "Greedy best-first search is accomplished by specifying f(n) = h(n)"
  391. h = memoize(h or problem.h, 'h')
  392. return best_first_graph_search(problem, h)
  393.  
  394.  
  395. def astar_search(problem, h=None):
  396. "A* search is best-first graph search with f(n) = g(n)+h(n)."
  397. h = memoize(h or problem.h, 'h')
  398. return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  399.  
  400.  
  401. # ________________________________________________________________________________________________________
  402. # Dopolnitelni prebaruvanja
  403. # Recursive_best_first_search e implementiran
  404. # Kako zadaca za studentite da gi implementiraat SMA* i IDA*
  405.  
  406. def recursive_best_first_search(problem, h=None):
  407. h = memoize(h or problem.h, 'h')
  408.  
  409. def RBFS(problem, node, flimit):
  410. if problem.goal_test(node.state):
  411. return node, 0 # (The second value is immaterial)
  412. successors = node.expand(problem)
  413. if len(successors) == 0:
  414. return None, infinity
  415. for s in successors:
  416. s.f = max(s.path_cost + h(s), node.f)
  417. while True:
  418. # Order by lowest f value
  419. successors.sort(key=lambda x: x.f)
  420. best = successors[0]
  421. if best.f > flimit:
  422. return None, best.f
  423. if len(successors) > 1:
  424. alternative = successors[1].f
  425. else:
  426. alternative = infinity
  427. result, best.f = RBFS(problem, best, min(flimit, alternative))
  428. if result is not None:
  429. return result, best.f
  430.  
  431. node = Node(problem.initial)
  432. node.f = h(node)
  433. result, bestf = RBFS(problem, node, infinity)
  434. return result
  435.  
  436.  
  437. # Graphs and Graph Problems
  438. import math
  439.  
  440.  
  441. def distance(a, b):
  442. """The distance between two (x, y) points."""
  443. return math.hypot((a[0] - b[0]), (a[1] - b[1]))
  444.  
  445.  
  446. class Graph:
  447. """A graph connects nodes (verticies) by edges (links). Each edge can also
  448. have a length associated with it. The constructor call is something like:
  449. g = Graph({'A': {'B': 1, 'C': 2})
  450. this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from
  451. A to B, and an edge of length 2 from A to C. You can also do:
  452. g = Graph({'A': {'B': 1, 'C': 2}, directed=False)
  453. This makes an undirected graph, so inverse links are also added. The graph
  454. stays undirected; if you add more links with g.connect('B', 'C', 3), then
  455. inverse link is also added. You can use g.nodes() to get a list of nodes,
  456. g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the
  457. length of the link from A to B. 'Lengths' can actually be any object at
  458. all, and nodes can be any hashable object."""
  459.  
  460. def __init__(self, dict=None, directed=True):
  461. self.dict = dict or {}
  462. self.directed = directed
  463. if not directed:
  464. self.make_undirected()
  465.  
  466. def make_undirected(self):
  467. """Make a digraph into an undirected graph by adding symmetric edges."""
  468. for a in list(self.dict.keys()):
  469. for (b, dist) in self.dict[a].items():
  470. self.connect1(b, a, dist)
  471.  
  472. def connect(self, A, B, distance=1):
  473. """Add a link from A and B of given distance, and also add the inverse
  474. link if the graph is undirected."""
  475. self.connect1(A, B, distance)
  476. if not self.directed:
  477. self.connect1(B, A, distance)
  478.  
  479. def connect1(self, A, B, distance):
  480. """Add a link from A to B of given distance, in one direction only."""
  481. self.dict.setdefault(A, {})[B] = distance
  482.  
  483. def get(self, a, b=None):
  484. """Return a link distance or a dict of {node: distance} entries.
  485. .get(a,b) returns the distance or None;
  486. .get(a) returns a dict of {node: distance} entries, possibly {}."""
  487. links = self.dict.setdefault(a, {})
  488. if b is None:
  489. return links
  490. else:
  491. return links.get(b)
  492.  
  493. def nodes(self):
  494. """Return a list of nodes in the graph."""
  495. return list(self.dict.keys())
  496.  
  497.  
  498. def UndirectedGraph(dict=None):
  499. """Build a Graph where every edge (including future ones) goes both ways."""
  500. return Graph(dict=dict, directed=False)
  501.  
  502.  
  503. class GraphProblem(Problem):
  504. """The problem of searching a graph from one node to another."""
  505.  
  506. def __init__(self, initial, goal, graph):
  507. Problem.__init__(self, initial, goal)
  508. self.graph = graph
  509.  
  510. def actions(self, A):
  511. """The actions at a graph node are just its neighbors."""
  512. return list(self.graph.get(A).keys())
  513.  
  514. def result(self, state, action):
  515. """The result of going to a neighbor is just that neighbor."""
  516. return action
  517.  
  518. def path_cost(self, cost_so_far, A, action, B):
  519. return cost_so_far + (self.graph.get(A, B) or infinity)
  520.  
  521. def h(self, node):
  522. """h function is straight-line distance from a node's state to goal."""
  523. locs = getattr(self.graph, 'locations', None)
  524. if locs:
  525. return int(distance(locs[node.state], locs[self.goal]))
  526. else:
  527. #print breadth_first_graph_search(GraphProblem(node.state, self.goal, graf)).solve()
  528. return len(breadth_first_graph_search(GraphProblem(node.state, self.goal, graf)).solve()) - 1
  529.  
  530.  
  531. Pocetok = input()
  532. Kraj = input()
  533.  
  534.  
  535.  
  536. graf = UndirectedGraph({
  537. "Frankfurt": {"Kassel": 173},
  538. "Munchen": {"Augsburg": 84, "Nurnberg": 167, "Kassel": 502},
  539. "Augsburg": {"Karlsruhe": 250},
  540. "Mannheim": {"Frankfurt": 85},
  541. "Nurnberg": {"Wurzburg": 103, "Stuttgart": 183},
  542. "Karlsruhe": {"Mannheim": 80},
  543. "Wurzburg": {"Erfurt": 186, "Frankfurt": 217}
  544. })
  545.  
  546. grafSolve = GraphProblem(Pocetok, Kraj, graf)
  547. answer = astar_search(grafSolve)
  548.  
  549. #print answer.solve()
  550.  
  551. if answer:
  552. print(answer.path_cost)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement