N = 5*10**4
n, m = 7, 7
x0, y0 = 3, 3
max_steps = 100
v = 1
from collections import defaultdict
from random import randint
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
hsh = defaultdict(int)
for _ in range(N):
x, y = x0, y0
step = 0
found = False
while step < max_steps:
r = randint(0, 3)
dx, dy = dirs[r]
x += v * dx
y += v * dy
step += 1
if x <= 0 or x >= n - 1 or y <= 0 or y >= m - 1:
hsh[step] += 1
found = True
break
if not found:
hsh[0] += max_steps
exp = sum( k * v for k, v in hsh.items()) / sum(hsh.values())
print(exp)
To embed this program on your website, copy the following code and paste it into your website's HTML: