我的教授给了我这段代码,我唯一要做的就是 TODO 区域。我对python还是很陌生,从来没有接触过这种类型的项目,所以我很困惑。这个项目的所有目的是获取绘制的图形图像。
import math, random, pylab
class Location(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def move(self, xc, yc):
return Location(self.x+float(xc), self.y+float(yc))
def getCoords(self):
return self.x, self.y
def getDist(self, other):
ox, oy = other.getCoords()
xDist = self.x - ox
yDist = self.y - oy
return math.sqrt(xDist**2 + yDist**2)
class CompassPt(object):
possibles = ('N', 'S', 'E', 'W')
def __init__(self, pt):
if pt in self.possibles: self.pt = pt
else: raise ValueError('in CompassPt.__init__')
def move(self, dist):
if self.pt == 'N': return (0, dist)
elif self.pt == 'S': return (0, -dist)
elif self.pt == 'E': return (dist, 0)
elif self.pt == 'W': return (-dist, 0)
else: raise ValueError('in CompassPt.move')
class Field(object):
def __init__(self, drunk, loc):
self.drunk = drunk
self.loc = loc
def move(self, cp, dist):
oldLoc = self.loc
xc, yc = cp.move(dist)
self.loc = oldLoc.move(xc, yc)
def getLoc(self):
return self.loc
def getDrunk(self):
return self.drunk
class Drunk(object):
def __init__(self, name):
self.name = name
def move(self, field, time = 1):
if field.getDrunk() != self:
raise ValueError('Drunk.move called with drunk not in field')
for i in range(time):
pt = CompassPt(random.choice(CompassPt.possibles))
field.move(pt, 1)
这是我需要做并尝试做的部分。到目前为止,我的图表没有移动大声笑。我在图表中间得到一个点,除非它在可能的情况下随机走在一个位置,哈哈。
# TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO
def performTrial(time, f):
start = f.getLoc()
# TODO
distances = [0.0]
for t in range(1, time + 1):
# TODO
f.getDrunk().move(f)
newLoc = f.getLoc()
distance = newLoc.getDist(start)
distances.append(distance)
xcoords, ycoords = distances[::2], distances[1::2]
return xcoords,ycoords
# END OF TODOEND OF TODO END OF TODO END OF TODO END OF TODO
这里的其余部分也是教授提供的
drunk = Drunk('Homer Simpson')
for i in range(1):
f = Field(drunk, Location(0, 0))
coords = performTrial(500, f)
print(coords)
pylab.plot(coords[0],coords[1],marker='^',linestyle=':',color='b')
pylab.title('Homer\'s Random Walk')
pylab.xlabel('Time')
pylab.ylabel('Distance from Origin')
pylab.show()
更新:修复了坐标,但现在我得到一个错误:
in _xy_from_xy(self, x, y)
235 y = np.atleast_1d(y)
236 if x.shape[0] != y.shape[0]:
--> 237 raise ValueError("x and y must have same first dimension")
238 if x.ndim > 2 or y.ndim > 2:
239 raise ValueError("x and y can be no greater than 2-D")
ValueError: x and y must have same first dimension