Python définit un ensemble de fonctions utilisées pour générer ou manipuler des nombres aléatoires via le module aléatoire.
Fonctions dans le module aléatoire s'appuient sur une fonction génératrice de nombres pseudo-aléatoires random(), qui génère un nombre flottant aléatoire compris entre 0,0 et 1,0. Ce type particulier de fonctions est utilisé dans de nombreux jeux, loteries ou toute application nécessitant une génération de nombres aléatoires.
Voyons un exemple de génération d'un nombre aléatoire en Python en utilisant le fonction random().
Python3
logique de transfert de registre
import> random> num>=> random.random()> print>(num)> |
>
>
Sortir:
0.30078080420602904>
Différentes façons de générer un nombre aléatoire en Python
Il existe plusieurs façons de générer des nombres aléatoires en Python en utilisant les fonctions du module aléatoire Python. Voyons quelques manières différentes.
Générer un nombre aléatoire en utilisant choix()
Python choix aléatoire() est une fonction intégrée au langage de programmation Python qui renvoie un élément aléatoire dans une liste, tuple , ou une chaîne .
Python3
# 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))> |
>
mysql afficher les utilisateurs
>
Sortir:
5 t>
Générer un nombre aléatoire à l'aide de randrange()
Le module random offre une fonction qui peut générer des nombres aléatoires Python à partir d'une plage spécifiée et permet également d'inclure des étapes, appelée randrange() .
Python3
Qu'est-ce qu'un ordinateur
# 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>))> |
>
>
Sortir:
A random number from list is : 4 A random number from range is : 41>
Générer un nombre aléatoire à l'aide de seed()
Python aléatoire.seed() La fonction est utilisée pour enregistrer l'état d'une fonction aléatoire afin qu'elle puisse générer des nombres aléatoires en Python lors de plusieurs exécutions du code sur la même machine ou sur des machines différentes (pour une valeur de départ spécifique). La valeur de départ est le numéro de valeur précédent généré par le générateur. Pour la première fois, lorsqu'il n'y a pas de valeur précédente, il utilise l'heure système actuelle.
Python3
# 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())> |
>
>
qui a inventé l'école
Sortir:
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>
Générer un nombre aléatoire à l'aide de shuffle()
La fonction shuffle() est utilisée pour mélanger une séquence (liste). Mélanger signifie changer la position des éléments de la séquence. Ici, l’opération de brassage est en place.
Python3
# 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>(>'
After the first shuffle : '>)> print>(sample_list)> # second shuffle> random.shuffle(sample_list)> print>(>'
After the second shuffle : '>)> print>(sample_list)> |
>
>
Sortir:
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']>
Générer un nombre aléatoire à l'aide de uniform()
La fonction uniform() est utilisée pour générer un nombre aléatoire Python à virgule flottante entre les nombres mentionnés dans ses arguments. Il faut deux arguments, limite inférieure (incluse dans la génération) et limite supérieure (non incluse dans la génération).
Python3
# 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>(>'
'>)> # 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>(>'
'>)> # 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>))> |
>
>
Sortir:
initialiseur de dictionnaire c#
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>