0

I Wrote the code for self avoiding random walk but when i ran in Terminal of PyCharm, the result was 0.0 for any parameters.What is the problem? anyone can help? The code is :

import sys
import random

n = int(sys.argv[1])
trials = int(sys.argv[2])
Dead_ends = 0

for t in range(trials):
a = [[False] * n] * n
x, y = n // 2, n // 2

while 0 < x < n - 1 and 0 < y < n - 1:
    if a[x - 1][y] and a[x + 1][y] and a[x][y + 1] and a[x][y - 1]:
        Dead_ends += 1
        break
    a[x][y] = True

    r = random.random()
    if r < 0.25:
        if not a[x + 1][y]: x += 1
    elif r < 0.5:
        if not a[x - 1][y]: x -= 1
    elif r < 0.75:
        if not a[x][y + 1]: y += 1
    else:
        if not a[x][y - 1]: y -= 1

print(100 * Dead_ends // trials)
James
  • 32,991
  • 4
  • 47
  • 70
MJavad
  • 15
  • 1
  • 1
  • 4
  • [Here's one problem.](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – user2357112 Apr 05 '20 at 11:50
  • Due to the faulty initialization of `a`, movement in the x direction is never possible - and once you've taken a single y step, only further steps with the same y direction are possible. So this doesn't generate a "random walk" at all, it's a direct beeline for the edge of the array - a dead end is impossible. – jasonharper Apr 05 '20 at 12:02
  • Try `a = [[False]*n for _ in range(n)]` to correct the faulty initialization others have mentioned. – DarrylG Apr 05 '20 at 12:16
  • Thank you all. i've corrected this and worked! – MJavad Apr 05 '20 at 12:35
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – dspencer Apr 05 '20 at 13:05

0 Answers0