如何生成随机路由



我是初学者,我遇到了编码挑战,我得到了以下方向:N,S,W,E

在挑战中,我需要生成 10 个随机步骤(方向(。另外,我不允许有重复的邻居。例如,不允许使用 [n,s,w,e,w,e,n,n,w,e]。

这是我的代码,但它无法正常工作。它生成路由但具有重复的邻居

import random
def road_generator():
directions = ['n','s','w','e']
road = []
for x in range(10):
road.append(random.choice(directions))
keep_going = True
while keep_going:
for x in range(1,len(road)):
if road[x] == road[x-1]:
road[x-1] = random.choice(directions)
else:
keep_going = False
print(road)
if __name__ == '__main__':
road_generator()

有人可以向我解释我的代码做错了什么以及如何解决这个问题吗?

谢谢:)

这是定义函数的一种方法:

import random
def road_generator():
directions = ['n','s','w','e']
road = []
while len(road)<10:
street = (random.choice(directions))
if not road:
road.append(street)
if road[-1] != street:
road.append(street)
return road
print(road_generator())

输出:

['e', 's', 'n', 'e', 'n', 'w', 'e', 'w', 'n', 'w']

您检查重复的邻居,但不是在 x 处更新,而是在 x-1 处更新。这可能会导致 x-1 和 x-2 中的重复。所以更新行

road[x-1] = random.choice(directions)

自:

road[x] = random.choice(directions)

应该做这个伎俩。

此外,一旦找到一对重复的邻居,就可以终止循环。稍后可能会有更多重复项。因此,您应该让循环运行到范围 10,并将代码更新为:

#remove keep_going variable
x = 1
while (x<len(road)):
if road[x] == road[x-1]:
road[x] = random.choice(directions)
else
x = x+1

这应该可以做到,您可以在将它们附加到列表的同时检查重复

import random
def road_generator():
directions = ['n','s','w','e']
road = []
for x in range(10):
road.append(random.choice(directions))
# to check duplicate neighbours 
if x!=0:
# This loop iterates until both values are same
while road[x] == road[x-1]:
road[x] = random.choice(directions)
print(road)
if __name__ == '__main__':
road_generator()

试试这个

import random
def road_generator():
directions = ['n','s','w','e']
road = []
for x in range(10):
temp = random.choice(directions)
while x > 0 and temp == road[x-1]:
temp = random.choice(directions)
road.append(temp)
print(road)

不是您特定问题的答案,但对您来说可能的不同方法

所以基本上你从一条随机路线开始,而不关心邻居。然后,您无限迭代路线,用新的随机方向替换任何相邻方向,直到您有一条好的路线。

也许您可以尝试重写它,这样您就不需要进行蛮力随机替换。

我建议你退后一步,弄清楚是什么真正造就了一个重复的邻居。然后尝试生成一条路线,而无需返回并检查它。

最新更新