class RandomWalk(): def __init__(self,point_num=5000): self.point_num = point_num self.xval = [0] self.yval = [0] def fill_walk(self): while len(self.xval)<self.point_num: x_direction = choice([1,-1]) step_num = choice([0,1,2,3,4]) xstep = x_direction * step_num y_direction = choice([1,-1]) step_num = choice([0,1,2,3,4]) ystep = y_direction * step_num if xstep == 0 and ystep==0: continue x_next = self.xval[-1] + xstep y_next = self.yval[-1] + ystep self.xval.append(x_next) self.yval.append(y_next) rw = RandomWalk(50000) rw.fill_walk() point_numbers = list(range(rw.point_num())) plt.scatter(rw.x_val,rw.y_val,c=point_numbers,cmap=plt.cm.Blues,edgecolor = 'none',s=2) plt.scatter(0,0,c='green',edgecolors='none',s=100) plt.scatter(rw.x_val[-1],rw.y_val[-1],c='red',edgecolor='none',s=100) plt.axes().get_xaxis().set_visible(False) plt.axes().get_xaxis().set_yisible(False) plt.show()修改代码
时间: 2023-11-12 18:06:35 浏览: 91
以下是修改后的代码:
```python
import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
def __init__(self, point_num=5000):
self.point_num = point_num
self.x_val = [0]
self.y_val = [0]
def fill_walk(self):
while len(self.x_val) < self.point_num:
x_direction = choice([1, -1])
x_step = choice([0, 1, 2, 3, 4])
x_val = x_direction * x_step
y_direction = choice([1, -1])
y_step = choice([0, 1, 2, 3, 4])
y_val = y_direction * y_step
if x_val == 0 and y_val == 0:
continue
next_x = self.x_val[-1] + x_val
next_y = self.y_val[-1] + y_val
self.x_val.append(next_x)
self.y_val.append(next_y)
rw = RandomWalk(50000)
rw.fill_walk()
point_numbers = list(range(rw.point_num))
plt.scatter(rw.x_val, rw.y_val, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=2)
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(rw.x_val[-1], rw.y_val[-1], c='red', edgecolor='none', s=100)
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
```
主要的修改包括:
1. `xval` 和 `yval` 改为 `x_val` 和 `y_val`,以符合 Python 的命名规范。
2. `rw.point_num()` 改为 `rw.point_num`,因为 `point_num` 是一个属性而不是方法。
3. `plt.axes().get_xaxis().set_yisible(False)` 改为 `plt.axes().get_yaxis().set_visible(False)`,因为原来的代码中打错了单词。
阅读全文