4
from random import randint

result = []
colors = {1: "Red", 2: "Green", 3: "Blue", 4: "White"}

while True:
    for key in colors:
        ball = randint(1,4)
        probability = (ball/10)
        result.append(probability)

    break

print(result)

This code gives me 4 values which is ok, but I'd like to have no repetitions. So if program took e.g "White", it won't include it to iteration. Any ideas?

7
  • Look into random.shuffle Commented Dec 14, 2018 at 15:06
  • 1
    the while loop is pointless; and i'm not clear what you're trying to do, you iterate over colors but never use key Commented Dec 14, 2018 at 15:07
  • If you have a bigger list, and you need to draw n elements from it without replacement, you can just shuffle the list, and take draw = big_list[:n]. Commented Dec 14, 2018 at 15:10
  • @L3viathan better to sample for that case Commented Dec 14, 2018 at 15:10
  • 1
    @Hiddenguy well you need to specify the sample size, read the docs when you try a new function docs.python.org/3/library/random.html#random.sample Commented Dec 14, 2018 at 15:13

2 Answers 2

2

If you have 4 values and you just want a random permutation of them, just use random.shuffle:

from random import shuffle

colors = {1: "Red", 2: "Green", 3: "Blue", 4: "White"}

balls = list(colors)
shuffle(balls)
result = [ball/10 for ball in balls]

print(result)

Another option (especially good with larger lists, because shuffling a list is "slow") is the use of random.sample:

from random import sample

colors = {1: "Red", 2: "Green", 3: "Blue", 4: "White"}

result = [ball/10 for ball in sample(colors, 4)]

print(result)
Sign up to request clarification or add additional context in comments.

Comments

0

You can check whether that particular value has been taken or not.

list_taken = []
number = randint(1,n)
while number in list_taken:
    number = randint(1,n)
list_taken.append(number)

So what above 4 lines of code do is, maintain a list of already taken values and repeat finding new values until it gets a new one.

Hope this helps!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.