Números aleatorios en Python

Python define un conjunto de funciones que se utilizan para generar o manipular números aleatorios a través del módulo aleatorio. 

Funciones en el módulo aleatorio Confíe en una función generadora de números pseudoaleatorios random() que genera un número flotante aleatorio entre 0,0 y 1,0. Este tipo particular de funciones se utiliza en muchos juegos de lotería o en cualquier aplicación que requiera una generación de números aleatorios.

Veamos un ejemplo de generación de un aleatorio. número en Python usando el función aleatoria ().

Python
   import   random   num   =   random  .  random  ()   print  (  num  )   

Producción:  

 0.30078080420602904  

Diferentes formas de generar un número aleatorio en Python

Hay varias formas de generar números aleatorios en Python utilizando las funciones del módulo aleatorio de Python. Veamos algunas formas diferentes.

Generando un número aleatorio usando elección()

Pitón elección.aleatoria() es una función incorporada en el lenguaje de programación Python que devuelve un elemento aleatorio de un lista tupla o cadena .

Python
   # import random   import   random   # prints a random value from the list   list1   =   [  1     2     3     4     5     6  ]   print  (  random  .  choice  (  list1  ))   # prints a random item from the string   string   =   'striver'   print  (  random  .  choice  (  string  ))   

Producción:

 5   
t

Generando un número aleatorio usando randrange()

El módulo aleatorio ofrece una función que puede generar números aleatorios de Python desde un rango específico y también permite espacio para incluir pasos llamados rango rand() .

Python
   # importing 'random' for random operations   import   random   # using choice() to generate a random number from a   # given list of numbers.   print  (  'A random number from list is : '     end  =  ''  )   print  (  random  .  choice  ([  1     4     8     10     3  ]))   # using randrange() to generate in range from 20   # to 50. The last parameter 3 is step size to skip   # three numbers when selecting.   print  (  'A random number from range is : '     end  =  ''  )   print  (  random  .  randrange  (  20     50     3  ))   

Producción:  

 A random number from list is : 4   
A random number from range is : 41

Generando un número aleatorio usando seed()

Pitón semilla.aleatoria() La función se utiliza para guardar el estado de una función aleatoria para que pueda generar algunos números aleatorios en Python en múltiples ejecuciones del código en la misma máquina o en diferentes máquinas (para un valor inicial específico). El valor inicial es el número de valor anterior generado por el generador. Por primera vez, cuando no hay un valor anterior, utiliza la hora actual del sistema.

Python
   # importing 'random' for random operations   import   random   # using random() to generate a random number   # between 0 and 1   print  (  'A random number between 0 and 1 is : '     end  =  ''  )   print  (  random  .  random  ())   # using seed() to seed a random number   random  .  seed  (  5  )   # printing mapped random number   print  (  'The mapped random number with 5 is : '     end  =  ''  )   print  (  random  .  random  ())   # using seed() to seed different random number   random  .  seed  (  7  )   # printing mapped random number   print  (  'The mapped random number with 7 is : '     end  =  ''  )   print  (  random  .  random  ())   # using seed() to seed to 5 again   random  .  seed  (  5  )   # printing mapped random number   print  (  'The mapped random number with 5 is : '     end  =  ''  )   print  (  random  .  random  ())   # using seed() to seed to 7 again   random  .  seed  (  7  )   # printing mapped random number   print  (  'The mapped random number with 7 is : '     end  =  ''  )   print  (  random  .  random  ())   

Producción:  

 A random number between 0 and 1 is : 0.510721762520941   
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237

Generando un número aleatorio usando shuffle()

El barajar() La función se utiliza para mezclar una secuencia (lista). Mezclar significa cambiar la posición de los elementos de la secuencia. Aquí se realiza la operación de barajado.

Python
   # import the random module   import   random   # declare a list   sample_list   =   [  'A'     'B'     'C'     'D'     'E'  ]   print  (  'Original list : '  )   print  (  sample_list  )   # first shuffle   random  .  shuffle  (  sample_list  )   print  (  '  n  After the first shuffle : '  )   print  (  sample_list  )   # second shuffle   random  .  shuffle  (  sample_list  )   print  (  '  n  After the second shuffle : '  )   print  (  sample_list  )   

Producción:

 Original list :    
['A' 'B' 'C' 'D' 'E']

After the first shuffle :
['A' 'B' 'E' 'C' 'D']

After the second shuffle :
['C' 'E' 'B' 'D' 'A']

Generando un número aleatorio usando uniforme()

El uniforme() La función se utiliza para generar un número aleatorio de Python de punto flotante entre los números mencionados en sus argumentos. Se necesitan dos argumentos: límite inferior (incluido en la generación) y límite superior (no incluido en la generación).

Python
   # Python code to demonstrate the working of   # shuffle() and uniform()   # importing 'random' for random operations   import   random   # Initializing list   li   =   [  1     4     5     10     2  ]   # Printing list before shuffling   print  (  'The list before shuffling is : '     end  =  ''  )   for   i   in   range  (  0     len  (  li  )):   print  (  li  [  i  ]   end  =  ' '  )   print  (  '  r  '  )   # using shuffle() to shuffle the list   random  .  shuffle  (  li  )   # Printing list after shuffling   print  (  'The list after shuffling is : '     end  =  ''  )   for   i   in   range  (  0     len  (  li  )):   print  (  li  [  i  ]   end  =  ' '  )   print  (  '  r  '  )   # using uniform() to generate random floating number in range   # prints number between 5 and 10   print  (  'The random floating point number between 5 and 10 is : '     end  =  ''  )   print  (  random  .  uniform  (  5     10  ))   

Producción:  

 The list before shuffling is : 1 4 5 10 2    
The list after shuffling is : 2 1 4 5 10
The random floating point number between 5 and 10 is : 5.183697823553464