logo

Nombres aleatoris en Python

Python defineix un conjunt de funcions que s'utilitzen per generar o manipular nombres aleatoris mitjançant el mòdul aleatori.

Funcions en el mòdul aleatori confieu en una funció generadora de nombres pseudoaleatoris random(), que genera un nombre flotant aleatori entre 0,0 i 1,0. Aquest tipus particular de funcions s'utilitza en molts jocs, loteries o qualsevol aplicació que requereixi una generació de números aleatoris.



Vegem un exemple de generació d'un nombre aleatori en Python utilitzant el funció aleatòria ().

cadena a int a Java

Python 3








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

>

>

Sortida:

0.30078080420602904>

Diferents maneres de generar un nombre aleatori en Python

Hi ha diverses maneres de generar números aleatoris a Python mitjançant les funcions del mòdul aleatori de Python. Vegem-ne algunes maneres diferents.

Generació d'un nombre aleatori utilitzant choice()

Python random.choice() és una funció integrada en el llenguatge de programació Python que retorna un element aleatori d'una llista, tupla , o corda .

Python 3




# 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))>

>

>

Sortida:

5 t>

Generar un nombre aleatori amb randrange()

El mòdul aleatori ofereix una funció que pot generar números aleatoris de Python a partir d'un interval especificat i també permet incloure espais per a passos, anomenat randrange() .

Python 3

matriu d'ordenació en java




# 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>))>

>

>

Sortida:

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

Generar un nombre aleatori amb seed()

Python random.seed() La funció s'utilitza per desar l'estat d'una funció aleatòria perquè pugui generar alguns números aleatoris en Python en múltiples execucions del codi a la mateixa màquina o en màquines diferents (per a un valor inicial específic). El valor llavor és el número de valor anterior generat pel generador. Per primera vegada quan no hi ha cap valor anterior, utilitza l'hora actual del sistema.

Python 3




# 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())>

>

>

Sortida:

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>

Generar un nombre aleatori mitjançant shuffle()

La funció shuffle() s'utilitza per barrejar una seqüència (llista). Barrejar significa canviar la posició dels elements de la seqüència. Aquí, l'operació de remenar està en marxa.

Python 3

números romans de l'1 al 100




# 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)>

>

ordre touch a linux
>

Sortida:

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']>

Generar un nombre aleatori amb uniform()

La funció uniform() s'utilitza per generar un nombre aleatori Python de coma flotant entre els nombres esmentats als seus arguments. Pren dos arguments, el límit inferior (inclòs a la generació) i el límit superior (no inclòs a la generació).

Python 3




# 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>))>

>

>

Sortida:

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>