如何生成随机路由

2024-05-14 15:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初学者,我遇到了一个编码挑战,我得到了以下指导: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()

有人能解释一下我的代码哪里出了问题,以及如何解决这个问题吗

谢谢:)


Tags: 代码in编码forifrangerandomgenerator
3条回答

试试这个

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)

这应该可以做到,你可以在将它们添加到列表中时检查重复性

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()

检查重复的邻居,但不是在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

相关问题 更多 >

    热门问题