dimanche 24 mai 2020

how to generate a random route

I am a beginner coder and i got a coding challenge where i got the following directions: N,S,W,E

in the challenge i need to generate a random 10 steps(directions) list and i am not allowed to have duplicate neighbors for example [n,s,w,e,w,e,n,n,w,e]

here is my code but it doesn't work eight, it stills generates me routes with duplicates

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

can someone please explain to me what i did wrong with my code and how can i fix this?

thanks :)




Aucun commentaire:

Enregistrer un commentaire