jeudi 16 mai 2019

How can I make this conditional for an 'almost' random walk?

I'm new on python. I'm following some challenges and one of them is to make a "random walk" in a type of lattice, like a matrix. I was actually trying at first to define the matrix and try to make a path by some condition with the nearest neighbors but I don't know how to do that.

So I tried this other approach. I have the steps in a loop, but I can't repeat the sites that were already used. I have a random condition to choose going on horizontal or vertical, and other to avoid sites outside the "matrix" range. I've made this other condition to avoid repeated sites, using a "while" since I need to redo the random value (i or j) if it is a repeated site. I've used a "for" to analyze every time the x and y arrays for repeated values simultaneously.

...

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

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

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

for k in range(passos):

    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):
            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)

Obviously it's not working, but I can't figure out the proper way to write, I'm just getting "invalid syntax" in all the tries that I've made. I think it would e simple by using some kind of matrix element random selection but I'm not sure how to do that too.

Thanks, I hope it is well explained.




Aucun commentaire:

Enregistrer un commentaire