简体   繁体   中英

I want to figure out how to make t

Code around the problem

import random 

from random import randint 

x = random.randint(1,3)

dis = {'5','6','9','4','7','8'}

f = ['Left' , 'Right' , 'Forward']

Problem area where i want the distance to go directly after the directions are revealed.

Each direction should only appear once.

for i in range(x):

    print('You can move ' + ''.join(" ".join(random.sample(f, 1) + random.sample(dis, 1 )))+" meters")

Overview

So essentially I am trying to generate strings that tell the user what directions they can move in and how far away it is based on random selection. The program however posed a challenge to me as I tried to get it to join the direction and distance together.Based on the number generated by x the program would place the associated directions and distances together.

For example: using this code produces this:

print('You can move ' + ''.join(" ".join(random.sample(f, x) + random.sample(dis, x )))+" meters")

You can move Forward Left Right 9 4 5 meters

The code under the section Code around the problem used a for loop that takes the randomly-generated number from x and makes it loop for that many times. I initially thought that this would be the final solution , however, i tried running it and the directions appeared more than once (which is a bit more than i had hoped for).Really and truly i would just like a solution that gives the direction and distance only once and in a format such as this:

You can move Right 5 meters

You can move Forward 9 meters

You can move Left 8 meters

How about this:

import random


dis = ['5','6','9','4','7','8']
f = ['Left' , 'Right' , 'Forward']

f_count = len(f)
for i in range(0, f_count):
    x = random.randint(0, len(f)-1)
    y = random.randint(0, len(dis)-1)
    dir = f[x]
    print('You can move ' + dir + " "+ dis[y] + " meters")
    f.pop(x)
    dis.pop(y)

You can use random.sample() method like in your example. Just use zip() method to tie randomly sampled values from dis and f together:

import random

dis = ['5', '6', '9', '4', '7', '8']
f = ['Left', 'Right', 'Forward']

for direction, d in zip(random.sample(f, len(f)), random.sample(dis, len(f))):
    print('You can move {} {} meters'.format(direction, d))

This will print for example:

You can move Forward 9 meters
You can move Left 5 meters
You can move Right 8 meters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM