How to draw numbers from a list, randomly and without repetitions?

Asked

Viewed 2,087 times

1

How do I draw 9 numbers in a list of 15, without repeating the numbers drawn? I use Python 3.8.

import random
for c in range (1, 16):
    n1 = str(input("Digite um nº: "))
l = [n1]
random.shuffle(l)
print("NÚMEROS ESCOLHIDOS: ", l)
print(" ", l)
print(" ", l)
print(" ", l)
print(" ", l)
print(" ", l)
print(" ", l)
print(" ", l)
print(" ", l)
  • Share what you’ve tried.

  • import Random for c in range (1, 16): n1 = str(input("Type a #: ") l = [n1] Random.shuffle(l) print(", l) print(" , ", l) print(" , "l) print(" , ", l) print(" , l) print(" ", l) print(" , ", l) print(", print(", ", l) print(" ", l)

  • I’ve tried a similar one, but it wasn’t tbm

  • Edit your question and put your code there

2 answers

4


Just use random.sample, which already guarantees that there will be no repetition.

But first a detail. You are asking the user to enter 15 numbers, so you need to save all of them on the list (the way you did, only the last one is put on it). And if you’re gonna use the range only to run something several times (and whatever the value used in the iteration), just do range(15).

And input already returns a string, so do str(input(...)) is redundant and unnecessary. If you want to ensure that a number has been entered, you can use int to convert the string to number (and capture the ValueError if no number is entered).

Then it would look like this:

from random import sample

numeros = []
for _ in range(15):
    while True:
        try:
            numeros.append(int(input("Digite um nº: ")))
            break # interrompe o while e vai para a próxima iteração do for
        except ValueError:
            print('não foi digitado um número')

print("NÚMEROS ESCOLHIDOS: ", sample(numeros, 9))

In the for i use _, which is a Python convention to indicate that the variable is not used in loop (because I’m only interested in doing something 15 times).

Then the while executes until a number is entered (because then it falls in the block except). If a number is entered, it is added to the list, the break interrupts the while and it goes to the next iteration of for.

Finally, having the list with the 15 numbers, I use random.sample to obtain the 9 numbers, without repetition.

  • THANK YOU!!! Now only I can make 50 options with the number mixed, thank you! I didn’t know about those tips you gave, thank you very much

  • @Aragon If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in all the answers you found useful.

  • eeey where you learned these things?

  • @Aragon If you are talking about the operation of the site, it was on [help]. If you are talking about Python, I always refer to documentation - and for specific questions, Stack Overflow itself has plenty of material :-)

0

To resolve this issue we can use the following code:

from random import sample


def sorteio_sem_repeticoes():
    return sorted(sample(range(1, 16), 9))


print(sorteio_sem_repeticoes())

Note that the values in this code are already preset, that is, this code will create a list with 9 elements drawn from within the closed interval [1, 15].

Now if you want to make a draw with a number of assorted drawn and with different range, you can use the following code:

from random import sample


def sorteio_sem_repeticoes(n, i, f):
    return sorted(sample(range(i, f + 1), n))


num = int(input('Desejas sortear quantos números? '))
ini = int(input('Digite o limite inicial do range: '))
fin = int(input('Digite o limite final do range: '))

print(sorteio_sem_repeticoes(num, ini, fin))

In this code we must inform the amount of values to be drawn and the lower and upper limits of the range. Important to note that with this last code we can draw n values of a range i corresponds to the lower end of the range and f corresponds to the upper limit.

  • 1

    Got it, thanks, it’s working really well, thank you!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.