python - 我怎样才能使这个条件为“几乎”随机游走?
问题描述
我是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)
显然它不起作用,但我无法找出正确的写作方式,我只是在我所做的所有尝试中都得到“无效的语法”。我认为使用某种矩阵元素随机选择会很简单,但我也不知道该怎么做。
谢谢,我希望它得到很好的解释。
解决方案
您可以使用 :
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))
推荐阅读
- reactjs - 我应该在哪里为 React 组件库添加配置文件
- python - 序列中最长连续元素的长度
- javascript - 移动菜单图标未显示在 Safari 或移动设备上
- r - 将 tmap 图例从基于符号更改为基于填充
- java - 验证处理时间的有效方法
- .net - 如何在 Winforms 应用程序中从 app.config 加载连接字符串后保护内存中的连接字符串
- haskell - 在列表理解中组合文本
- javascript - react-native-init 配置文件 - 不确定要编辑哪些绝对导入路径
- visual-studio-code - 如何通过 Fiddler 捕获 Visual Studio Code 流量?
- r - 从具有两列 R 的数据框创建邻接