Python 3.x 为什么我在这个随机游走测试中使用Python3得到了所有的单元一?
我是一个python初学者,我想知道为什么我在下面的脚本中得到了所有的单元。我希望得到一些1-10之间的整数Python 3.x 为什么我在这个随机游走测试中使用Python3得到了所有的单元一?,python-3.x,Python 3.x,我是一个python初学者,我想知道为什么我在下面的脚本中得到了所有的单元。我希望得到一些1-10之间的整数 import random def random_walk(n): """Return coordinates after 'n' block random walk""" x, y = 0, 0 for i in range(n): (dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1,
import random
def random_walk(n):
"""Return coordinates after 'n' block random walk"""
x, y = 0, 0
for i in range(n):
(dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
x += dx
y += dy
return (x, y)
for i in range(5):
walk = random_walk(10)
print(walk, "Distance from home = ",
abs(walk[0]) + abs(walk[1]))
输出:
(1, 1) Distance from home = 2
(-1, 1) Distance from home = 2
(-3, 3) Distance from home = 6
(0, -2) Distance from home = 2
(1, 3) Distance from home = 4
(-1,0)与原点的距离=1
距原点的(-1,0)距离=1
距原点的(-1,0)距离=1
距原点的(-1,0)距离=1
(0,-1)距原点的距离=1
我认为这句话:
return (x, y)
应在循环之外:
import random
def random_walk(n):
"""Return coordinates after 'n' block random walk"""
x, y = 0, 0
for i in range(n):
(dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
x += dx
y += dy
return (x, y)
for i in range(5):
walk = random_walk(10)
print(walk, "Distance from home = ",
abs(walk[0]) + abs(walk[1]))
输出:
(1, 1) Distance from home = 2
(-1, 1) Distance from home = 2
(-3, 3) Distance from home = 6
(0, -2) Distance from home = 2
(1, 3) Distance from home = 4
谢谢我刚想出来。