首页 > 解决方案 > 我怎样才能使这个条件为“几乎”随机游走?

问题描述

我是python新手。我正在接受一些挑战,其中一个是在一种格子中进行“随机游走”,比如矩阵。我实际上最初是在尝试定义矩阵并尝试通过某些条件与最近的邻居建立路径,但我不知道该怎么做。

所以我尝试了另一种方法。我有循环中的步骤,但我不能重复已经使用的站点。我有一个随机条件来选择水平或垂直,以及其他避免“矩阵”范围之外的站点。我已经使用“while”来避免重复站点,因为如果它是重复站点,我需要重做随机值(i 或 j)。我每次都使用“for”来同时分析 x 和 y 数组的重复值。

... #before here there were some start points definitions, etc

for k in range(steps):

    if rd.randint(1,2) == 1:
        i = rd.randint(max(i-1,0),min(i+1,n))
        while ((for w in x, x[w] = i) and (for w in y, y[w] = j):
        #this "while" above isn't good, but it was to see if the w term 
        #of the x and y array were already a pair used in some previous 
        #iteration
            i = rd.randint(max(i-1,0),min(i+1,n))
    else:    
        j = rd.randint(max(j-1,0),min(j+1,n))
        while ((for w in x, x[w] = i) and (for w in y, y[w] = j):
            j = rd.randint(max(j-1,0),min(j+1,n))


    x.append(i)
    y.append(j)

显然它不起作用,但我无法找出正确的写作方式,我只是在我所做的所有尝试中都得到“无效的语法”。我认为使用某种矩阵元素随机选择会很简单,但我也不知道该怎么做。

谢谢,我希望它得到很好的解释。

标签: pythonrandom

解决方案


您可以使用 :

if i not in x:

检查它是否在您的列表中。不需要 for 循环。这是您可以做到的一种方法:

i = rd.randint(0,n)
j = rd.randint(0,n)

print("The start point is S[{},{}]".format(i,j))
x = []
y=[]
x.append(i)
y.append(j)

for k in range(10):

    if rd.randint(1,2) == 1:
        new_i = rd.randint(max(i-1,0),min(i+1,n))
        if new_i not in x:
            i = new_i
        else :
            print("I'm not moving")
    else:    
        new_j = rd.randint(max(j-1,0),min(j+1,n))
        if new_j not in y:
            j = new_j
        else :
            print("I'm not moving")


    x.append(i)
    y.append(j)
    print("My current position is x = {}; y = {}".format(i,j))

推荐阅读