How to avoid repetition of numbers randomly in a range with python3?

0

I have in mind to make a kind of game type elections where the votes are generated randomly, the problem is that I can not get random to generate random numbers within a range, for example I tell random to interchange 1 and 2 randomly and what I get is that in a whole range of the same number ... I leave a screen to be clear ...!

    
asked by windtux22 12.08.2016 в 15:21
source

3 answers

1

What happens is that you are generating the random number outside the cycle. That is, the function randint is only executed once generating a single random number (which you saved in the variable valor ).

To generate a different random number, you must put the randint function within the cycle, for example:

import random
for a in range(11):
  valor = random.randint(1, 2) # fijate que esta dentro del ciclo
  print(a, valor)
    
answered by 12.08.2016 / 17:46
source
0

Try the following code:

import random

for a in range(11):
    print(a, random.randint(1,2))
    
answered by 12.08.2016 в 16:48
-1

If the range is not very large, you can create a Boolean array, called for example "available", initialized to true, which will indicate which numbers of the range are available, and a variable "available" with the number of random numbers that we have available, initialized in available.length, then choose a random number between 1 and "available", and scroll "available" looking for the position "true" number "random", the position will be the answer, we assign "false" in the "random" position and decrease "available". In this way, skipping the available "false" will only come out once. Sorry it does not show python code, but I do not know it. Example in javascript:

<!DOCTYPE html>
<button onclick="aleatorio()">Mostrar numero aleatorio</button>
<button onclick="resetear()">Resetear rango</button>

<SCRIPT>
var rango=11; // de 0 a 10;
var disponible=[];
var disponibles;

function resetear(){
	for (var i=0; i<rango; i++) disponible[i]=true;
	disponibles=rango;
}

function aleatorio(){
	if (!disponibles) {document.body.innerHTML+="Fin "; return;}
	var azar=Math.floor(Math.random()*disponibles)+1;
	var contador=0, posicion=0;
	while (contador<azar) if (disponible[posicion++]) contador++;
	disponible[--posicion]=false;
	disponibles--;
	document.body.innerHTML+=posicion+" ";
}
resetear();
</SCRIPT>
    
answered by 12.08.2016 в 16:39