Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

480
Visualizações
Generate random number in range excluding some numbers

Is there a simple way in Python to generate a random number in a range excluding some subset of numbers in that range?

For example, I know that you can generate a random number between 0 and 9 with:

from random import randint
randint(0,9)

What if I have a list, e.g. exclude=[2,5,7], that I don't want to be returned?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Try this:

from random import choice

print choice([i for i in range(0,9) if i not in [2,5,7]])
over 4 years ago · Santiago Trujillo Relatório

0

Try with something like this:

from random import randint

def random_exclude(*exclude):
  exclude = set(exclude)
  randInt = randint(0,9)
  return my_custom_random() if randInt in exclude else randInt 
  
print(random_exclude(2, 5, 7))
over 4 years ago · Santiago Trujillo Relatório

0

If you have larger lists, i would recommend to use set operations because they are noticeable faster than the recomended answer.

random.choice(list(set([x for x in range(0, 9)]) - set(to_exclude)))

I took took a few tests with both the accepted answer and my code above.

For each test i did 50 iterations and measured the average time. For testing i used a range of 999999.

to_exclude size 10 elements:
Accepted answer = 0.1782s
This answer = 0.0953s

to_exclude size 100 elements:
Accepted answer = 01.2353s
This answer = 00.1117s

to_exclude size 1000 elements:
Accepted answer = 10.4576s
This answer = 00.1009s

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda