I have to create a self avoiding lattice path which moves in 4 directions (North, East, West, South). I have written a function for this:
n=int(input())
edges = [[1, 0], [0, 1], [-1, 0], [0, -1]]
make_step = lambda point, edge: [x+y for x,y in zip(point, edge)]
path=[[0,0]]
x_coo=[0]
y_coo=[0]
for i in range(n):
next_points = [make_step(path[-1], edge) for edge in edges]
allowed_points = [point for point in next_points if point not in path]
p=rand.choice(allowed_points)
path.append(p)
x_coo.append(p[0])
y_coo.append(p[1])
plt.plot(x_coo,y_coo)
It works well until the input is 60 but gives an error when input is greater than 0.
IndexError Traceback (most recent call last)
<ipython-input-15-a4a59bcce6b0> in <module>
10 allowed_points = [point for point in next_points if point not in path]
11
---> 12 p=rand.choice(allowed_points)
13
14 path.append(p)
~\anaconda3\lib\random.py in choice(self, seq)
259 i = self._randbelow(len(seq))
260 except ValueError:
--> 261 raise IndexError('Cannot choose from an empty sequence') from None
262 return seq[i]
263
IndexError: Cannot choose from an empty sequence
Someone please help me resolve this error.
Aucun commentaire:
Enregistrer un commentaire