Advertisement
Guest User

Untitled

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