MCPcopy
hub / github.com/TheAlgorithms/Python / astar

Function astar

machine_learning/astar.py:89–133  ·  view source on GitHub ↗

Implementation of a start algorithm. world : Object of the world object. start : Object of the cell as start position. stop : Object of the cell as goal position. >>> p = Gridworld() >>> start = Cell() >>> start.position = (0,0) >>> goal = Cell() >>> goal.posi

(world, start, goal)

Source from the content-addressed store, hash-verified

87
88
89def astar(world, start, goal):
90 """
91 Implementation of a start algorithm.
92 world : Object of the world object.
93 start : Object of the cell as start position.
94 stop : Object of the cell as goal position.
95
96 >>> p = Gridworld()
97 >>> start = Cell()
98 >>> start.position = (0,0)
99 >>> goal = Cell()
100 >>> goal.position = (4,4)
101 >>> astar(p, start, goal)
102 [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
103 """
104 _open = []
105 _closed = []
106 _open.append(start)
107
108 while _open:
109 min_f = np.argmin([n.f for n in _open])
110 current = _open[min_f]
111 _closed.append(_open.pop(min_f))
112 if current == goal:
113 break
114 for n in world.get_neighbours(current):
115 for c in _closed:
116 if c == n:
117 continue
118 n.g = current.g + 1
119 x1, y1 = n.position
120 x2, y2 = goal.position
121 n.h = (y2 - y1) ** 2 + (x2 - x1) ** 2
122 n.f = n.h + n.g
123
124 for c in _open:
125 if c == n and c.f < n.f:
126 continue
127 _open.append(n)
128 path = []
129 while current.parent is not None:
130 path.append(current.position)
131 current = current.parent
132 path.append(current.position)
133 return path[::-1]
134
135
136if __name__ == "__main__":

Callers 1

astar.pyFile · 0.85

Calls 3

get_neighboursMethod · 0.80
appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected