"Python Module Learning" 3, Random module

Source: Internet
Author: User
Tags shuffle

Reference: 1, official website; 2, others '

Here's how to do the Random module:

1Random.seed (A=none, version=2)#Initializes a pseudo-random number generator. If a or a=none is not provided, the system time is used as the seed. If a is an integer, it is used as a seed. 2Random.getstate ()#an object that returns the internal state of a current generator3Random.setstate (state)#Pass in a state object previously obtained using the GetState method, allowing the generator to revert to this state. 4Random.getrandbits (k)#returns an integer between range (0,2**k), equivalent to Randrange (0,2**k)5Random.randrange (STOP)#returns an integer between range (0,stop)6Random.randrange (Start, stop[, step])#returns an integer between range (start,stop), plus step, similar to Range (0,10,2)7Random.randint (A, B)#returns an integer between range (a,b+1) that is equivalent to Hugin range (a,b+1)8Random.choice (seq)#randomly selects an element from a non-empty sequence seq. If seq is empty, the indexerror exception pops up. 9Random.choices (population, Weights=none, *, Cum_weights=none, k=1)#version 3.6 is new. Randomly extracting k elements from a population cluster (repeatable). Weights is a list of relative weights, cum_weights is a cumulative weight, and two parameters cannot be present at the same time. TenRandom.shuffle (x[, Random])#randomly disrupts the order of the elements within the sequence x. Only for mutable sequences, for immutable sequences, use the sample () method below.  OneRandom.sample (population, K)#randomly extracting k non-repeating elements from a population sample or collection to form a new sequence. Often used for non-repeating random sampling. Returns a new sequence that does not break the original sequence. To randomly extract a certain number of integers from an integer interval, use a similar approach to sample (range (10000000), k=60), which is very efficient and space-saving. If k is greater than the length of population, the valueerror exception pops up.  ARandom.random ()#returns a floating-point number in the [0.0, 1.0) interval between left and right open -Random.uniform (A, B)#returns a floating-point number between A and B. If a>b, it is a floating-point number between B and a. Both A and b here are likely to appear in the results.  -Random.triangular (Low, high, mode)#returns the random number of the triangle distribution of a low <= N <=high. The parameter mode indicates the location of the majority occurrence.  theRandom.betavariate (alpha, Beta)#Beta distribution. The returned result is between 0~1 -Random.expovariate (LAMBD)#Exponential distribution -Random.gammavariate (alpha, Beta)#Gamma Distribution -Random.gauss (Mu, sigma)#Gaussian distribution +Random.lognormvariate (Mu, sigma)#Logarithmic normal distribution -Random.normalvariate (Mu, sigma)#Normal Distribution +Random.vonmisesvariate (Mu, kappa)#Kappa Distribution ARandom.paretovariate (Alpha)#Pareto Distribution atRandom.weibullvariate (alpha, Beta)#Weibull Distribution

Instance:

Basic Examples:

>>> Random ()#Random floating point: 0.0 <= x < 1.00.37444887175646646>>> Uniform (2.5, 10.0)#Random floating point: 2.5 <= x < 10.03.1800146073117523>>> Randrange (10)#An integer of 0-9:7>>> randrange (0, 101, 2)#0-100 of even26>>> Choice (['win','lose','Draw'])#randomly select an element from a sequence'Draw'>>> deck ='ace three four'. Split ()>>> Shuffle (deck)#Shuffle the sequence to change the original sequence>>>deck[' Four',' Both','Ace','three']>>> sample ([Ten, +, +, +], k=4)#extracts a specified number of samples without altering the original sequence and generates a new sequence[40, 10, 50, 30]>>>#6 rotations red-black green roulette (with weighted repeatable sampling), without destroying the original sequence, weight[18,18,2]>>> Choices (['Red','Black','Green'], [2], k=6)['Red','Green','Black','Black','Red','Black']>>>#Texas hold ' em calculation probability deal cards without replacement from a deck of playing cards>>>#and determine the proportion of cards with a ten-value>>>#(a ten, Jack, Queen, or king).>>> deck = collections. Counter (tens=16, low_cards=36)>>> seen = sample (List (Deck.elements ()), k=20)>>> Seen.count ('Tens')/200.15>>>#simulation probability estimate the probability of getting 5 or more heads from 7 spins>>>#of a biased coin that settles on heads 60% of the time. ' The probability of H ' is 0.6, and the probability of "T" is 1-0.6>>> trial =Lambda: Choices ('HT', cum_weights= (0.60, 1.00), k=7). Count ('H') >= 5>>> sum (Trial () forIinchRange (10000))/100000.4169>>>#probability of the median of 5 samples being in middle and quartiles>>> trial =Lambda: 2500 <= Sorted (choices (range (10000), k=5)) [2] < 7500>>> sum (Trial () forIinchRange (10000))/100000.7958
>>> fromStatisticsImportMean>>> fromRandomImportChoices>>> data=1,2,4,4,10>>> means=Sorted (mean (choices (k=5) for i in range (20 ) # mean is the average  >>> print ( f ' The sample mean of {mean (data):. 1f} has a 90% c Onfidence ' f ' interval from {means[1]:.1f} to Span class= "si" >{means[-2]:.1f} ' ) # the F usage here   

Here is a program that generates a random 4-bit verification code with a A-Z and a number 0-9 in uppercase letters

1 ImportRandom2  3Checkcode ="'4  forIinchRange (4):5Current = Random.randrange (0,4)6     ifCurrent! =I:7temp = Chr (Random.randint (65,90))8     Else:9temp = Random.randint (0,9)TenCheckcode + =Str (temp) One Print(Checkcode)

The following is the code that generates a random sequence of alphanumeric numbers of a specified length:

Importrandom, Stringdefgen_random_string (length):#the number of numbers is randomly generatedNum_of_numeric = Random.randint (1,length-1)    #All that's left is letters.Num_of_letter = Length-Num_of_numeric#randomly generate numbersNumerics = [Random.choice (string.digits) forIinchrange (num_of_numeric)]#randomly generated lettersLetters = [Random.choice (string.ascii_letters) forIinchrange (num_of_letter)]#Combine bothAll_chars = Numerics +Letters#Shufflerandom.shuffle (all_chars)#Generate final Stringresult ="'. join ([i forIinchAll_chars]) returnresultif __name__=='__main__':    Print(Gen_random_string (64))

"Python Module Learning" 3, Random module

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.