# 重构函数失败

0

import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
'''一个生成随机漫步数据的类'''
def init(self,num_points):
self.num_points = num_points
#所有的随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
self.step = 0
def get_step(self):
direction = choice([1, -1]) # 随机选择向左向右两个方向
distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8]) # 随机选择移动的距离
self.step = direction * distance # 每次移动的步长
def fill_walk(self):
'''定义一个循环，直到达到给定的点数'''
while len(self.x_values) < self.num_points:
x_step = get_step()
y_step = get_step()
#x_direction = choice([1, -1])
#x_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8])
#x_step = x_direction * x_distance
#y_direction = choice([1, -1])
#y_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8])
#y_step = y_direction * y_distance
#拒绝原地踏步
if x_step and y_step == 0:
continue
#计算下一个点的xy值,用列表的最后一个值加上步长
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)

Charlie大夫 | 初学一级 | 园豆：176

0

``````import matplotlib.pyplot as plt
from random import choice

class RandomWalk():
'''一个生成随机漫步数据的类'''
def init(self,num_points):
self.num_points = num_points
#所有的随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
self.step = 0

def get_step(self):
direction = choice([1, -1]) # 随机选择向左向右两个方向
distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8]) # 随机选择移动的距离
self.step = direction * distance # 每次移动的步长

def fill_walk(self):
'''定义一个循环，直到达到给定的点数'''
while len(self.x_values) < self.num_points:
x_step = get_step()
y_step = get_step()
#x_direction = choice([1, -1])
#x_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8])
#x_step = x_direction * x_distance
#y_direction = choice([1, -1])
#y_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8])
#y_step = y_direction * y_distance
#拒绝原地踏步
if x_step and y_step == 0:
continue
#计算下一个点的xy值,用列表的最后一个值加上步长
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)``````

您需要登录以后才能回答，未注册用户请先注册