0 ratings0% found this document useful (0 votes) 39 views3 pagesIT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Bing
‘Sue, Team explain cach method of the Python random module with an example. @
“The random module is used to generate pseudo-random numbers, which means thy ae not tly random but depend on a sed valuc. You can use the seed) method to set
{he sed value fr the random number porarator Tis will make the random nambets predictable and reprodueile For example
soncon-reeetS) 4 st she soec value £9 3
Sriretrandon-tandar))"s geint'a randon Flost Between @ and 2
Grirstrandoncrandar)) # point anotnes random float between @ and 3
uur:
1 you un this code again, you will gt the same ouput Ifyou change the seed value or donot speci it, you will ge diferent outp
"The gestalt) method returns an oct tha represents the cuent internal sate ofthe rendom number generator: You can ws this oes to save or relae the ile ater For
example
srancon-seee(3) # et the seed value £9 3
State's randongeistate() F sove the cutpent stat
brirs¢randon radon) prine’s random lost between @ and 2
Fancon-setseate(state) # restore the arevious 3
Dprirstrandonsrandor)) # print the sme rnin float a6 before
utp:
“The getrandbits) method returns an integer wih a specified numberof bis, You can use thie method to generate large random integers o binary numbers Fr example:
rirc(randen-getranbsts(10)) # point 2 random soteger mith 18 bits
Srsretbanteandon getranabies(s8))) © pine» random birssy number with 10 O88
utp:
"he randrange) method returns random integer between a given range. You can also specify a tp size o skip some numbers in the range. For example
Drirctrendow randrange(JO)) # grint a randonsnteger between @ and 9 (inclusive)
Srirstrandon-randrage(ty 20})"s print a rand Sneoper Seeneey 1 aie (inelurtve)
Srirstrandon-randrange(®, 28, 2))"4 pein ndon ever integer beeen Ward 38 (2aclusive)
uur:
“The randint) method is similar to the randrange() method, but it always includes both endpoints ofthe rang. For example
rirctrandon rain, 289) # prints randon Integer between 1
Drirstranden-rardint(b, 10})'# brant 10 (the only possible value)
28 (anctusive)
up:
“The choice method returns a random element ffom a given sequence, such as lis, tuple, or sring. For example:
foiors © [ered geen", “blue, *yelbow")
sieve nich coats) prt Pde color fron se st
Srirstrandonsence(nane)) # print + candon character fron the string
utr:
“The choicest) method tums list of multiple random elements fom a given sequence, with or without replacement, You can also specify weights or probabiities for each
clement to male some elements more likely thas eters. For exam
frasce ©'[Sapple, "banana", “sheory", “orange"l
Srirs(randon ehetZea(fratts, bad)) t Seine elise of three randon fruits with reploccnent (euplicates are possibie)
Grinstrandon-ehoes(eraite, wetghceel2, 1, 1y Alp #e3)) % prane 4 list ot these randon fuste wich replaceneat an disferent weights (apple 4s twice a6 MKely
ouput:
Cshery'y, “apple, “banana
U-Spoie’, sappie', "orange"
“The shu) method lakes @ sequence and retums the Sequence in
slit. For example
random orde. The original sequence is modified in place, s0 you nee to pass @ mutable sequence such
rimbers'= "Tir 2, 3, 51‘Pandos.shuffletnuabers) @ shuffle the list in place
Dpriretnamers) & print the shuttled Tise
ovsput
(asa
“Te sample) method res given sample often chosen rom a sequence without replacement. The ginal sequence i ot modified. For example:
rinttrabdm-sooleletecrsy5)) Frnt a Lst of fve random Setters without ceslacentnt
ouput
C3 WS st 8 om
‘The endam) method retusa rnd lat mmber betwee and 1. Ths is the most base method ofthe radon module, For example
prirctraedon randor) # point 9 canon Flot oesusen 8 and 2
utp
"The uniform) method retusa random float number between two given parameters, bth inclusive, You can us this method to generate random numbers in any ange. For
example
Drirctrendonruntforn(1, 199) # print a randon float between 1 and $8 (snclustve)
Srinstrandoncunforn-3, 3}} # print 2 rand floa: beteeea “sand (inclusive)
ouput:
“The tangular) method seta # random float number between two given parameters, wih bias wards ane extreme, You ea alo sla me parameter lo specify he
midpoint between the two other parsmeters, The default mode Is the mean ofthe two parameters, For example:
rirc(randon trLagular(3, 20)) # print 2 random flout betwean and 20 (Laclusive) wlth 2 nean of 55
Srirctranden-tolanglar(2, 18, 3))"# arine randon float Setueen tana 48 (inclusive) with mode of 3 (nore likely to ¥e closer to 3)
ouput
“The botaverat() method rus «random float umber between 0 and 1 bated onthe Beta distribution (usd in sais), The Beta distribution is defined by to shape
parame, alpha and bla, which contol the shape ofthe curve. For example
iort natpletite.pyplot as tt
dats" [randon betavardateta, 5) for | in sango3@6@)) " "
- plot the nistogran of the cata
prtsniet (date, binn29)
Siecesttetncta distrtovtion with alpha? and betes")
Biesshowt)
up
“The expovariatl) method rtuns «random lat aumber based on the Exponential dstiution (used in satstics). The Exponential distribution i defined by one parameter,
Jamba, which corel the rte of change For exemple
IMport natplotite.pypiot as kt
1 generate 1000 random numbers based on the Gxonential distetbution wlth Zankdo8.s
ats"= [randoncexpovariatet@.s) for _ in rnge(a@ae)]
SrbsnistGdata, eines)
Diecestiecextorentias distribution with Laoeare.5°)
bisverout)
utp:
'Exponcasildistebuton with lambda=0.5)
“The gammavariate() method reams a random float number based onthe Gamma dstibtion (sed in stasis). The Gamma distribution is defined by swo parameter,
ipa and bet, whieh contol te shipe and seale ofthe curve, For example
iort natpletite.pypiot as tt
1 geverate 1900 random muabers based on the Ganma distrsbution with alpha-? and beta-2
dats" [randon-eamavsesave(2, 2) for") Sn eage(3ba9)]
- plot the nistogran of the cata
SubsRdet (dete, einsse)
Suesesedet-coins clserioution with alphacd ane beta
Siesshow)
")
output:
"Gamma dseibuion wit
"The gauss) method returns a andom float number based onthe Geussin distribution (used in probability theories) The Gausian distribution i also known asthe normal
Aislin oth bell eurve Its defined by two parameters, mean and standard deviation, which contol the cenlr and spread a the curve. For exampleItport watploclt8.pyplot as kt
4 generate 1000 random runbers based on the Gaussian distribution wlth nea%-8 and Standard deviation=t
Gats'> [randon-gnuss(, 1) for = if range(108)]
presnsee(dets, bine29)
Sitlestie('cniasion aateibutton with pe
biessrewt)
and standard devistion-2")
ouput
'Grussiondstrbuton with mean-0 and standard devaton=I]
"The lognarmariate) method returns random Most number based