随机漫步在python中

时间:2016-02-15 13:18:16

标签: python random

我正在尝试在python中实现随机游走。这是我得到的错误。我觉得我的实施是错误的,或者至少不是最好的。有人可以看看它。请记住,我是python的初学者,这就是我认为有人会编写代码的方式,所以我可以完全关闭。

in randomWalk(stepSize, stepNumber)
     37     for _ in range(stepNumber):
     38         r = randint(1,4)
---> 39         x,y = movement[r]
     40         xList.append(x)
     41         yList.append(y)
TypeError: 'function' object is not iterable

这是我的代码

from pylab import *
import numpy as np
import matplotlib.pyplot as plt
import random as rnd
matplotlib.rcParams.update({'font.size': 20})

x = 0.
y = 0.
xList = []
yList = []
def goRight(stepSize, y):
    direction = np.cos(0)
    x = stepSize*direction
    return [x,y]

def goUp(stepSize, x):
    direction = np.cos(90)
    y = stepSize*direction
    return [x,y]

def goLeft(stepSize, y):
    direction = np.cos(180)
    x = stepSize*direction
    return [x,y]

def goDown(stepSize, x):
    direction = np.cos(270)
    y = stepSize*direction
    return [x,y]

def randomWalk(stepSize, stepNumber):
    movement = {1: goRight, 
                2: goUp, 
                3: goLeft, 
                4: goDown}

    for _ in range(stepNumber):
        r = randint(1,4)
        x,y = movement[r]
        xList.append(x)
        yList.append(y)


    plt.ioff()
    plot(x, y)
    plt.show()


randomWalk(1.,4)

3 个答案:

答案 0 :(得分:3)

您正在将函数放入dict movementmovement[r]没有调用该函数,只访问它们。你的基本做法是:

x, y = goDown

如果要调用该行中的函数,则必须添加括号和参数,如:

x, y = movement[r](stepSize, x)

这表明您的设计存在问题,因为某些功能需要x,而某些功能需要y。您可以通过让所有函数同时采用坐标x和y来解决这个问题,然后您的行应该像

一样
x, y = movement[r](stepSize, x, y)

答案 1 :(得分:1)

问题在于

x,y = movement[r]

字典移动是当你调用移动[r]时函数的一个列表,只返回一个函数,但在这里你试图解压缩它。相反,我认为你想要:

 x,y = movement[r](stepSize)

这会调用你的功能,所以返回你想要的坐标。 您还需要将所有步骤方法更改为仅采用一个参数...

答案 2 :(得分:0)

你不能在这样的词典中调用一个函数,而是使用它:

Task