Python's Random module detailed

Source: Internet
Author: User
Tags random seed shuffle
This article mainly introduces Python's random module related content, has the certain reference value, needs the friend to be possible the reference, hoped can help everybody.

Random module

Used to generate pseudo-random numbers

The real random number (or random event) is generated randomly in the course of the experiment, and the result is unpredictable and not visible. The random function in the computer is simulated by some algorithm, and the result is definite and visible. We can think of this predictable result as the probability of its occurrence is 100%. So the "random number" generated by the computer random function is not random, it is a pseudo-random number.

The pseudo-random number of a computer is a numerical value calculated by a random seed based on a certain computational method. Therefore, as long as the calculation method must be, random seed must, then the resulting random number is fixed.

As long as the user or third party does not set a random seed, the random seed comes from the system clock by default.

Python's library uses a common algorithm at the bottom, and after a long test, reliability doesn't have to be said, but it must never be used for password-related functions.

First, the Basic method

random.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.

random.getstate()
An object that returns the internal state of a current generator

random.setstate(state)
Pass in a state object previously obtained using the GetState method, allowing the generator to revert to this state.

random.getrandbits(k)
Returns an integer that is not more than the K bit of the Python Integer (decimal), such as k=10, which results in 0~2^10.

Second, the method for integer

random.randrange(stop)

random.randrange(start, stop[, step])
is equivalent to choice (range (start, stop, step)), but does not actually create a Range object.

random.randint(a, b)
Returns a random integer n of a <= n <= b. Equivalent to Randrange (A, b+1)

Third, the method for the sequence class structure

random.choice(seq)
Randomly selects an element from a non-empty sequence seq. If seq is empty, the indexerror exception pops up.

random.choices(population, weights=None, *, cum_weights=None, k=1)
Version 3.6 is new. Randomly extracting k elements from a population cluster. Weights is a list of relative weights, cum_weights is a cumulative weight, and two parameters cannot be present at the same time.

random.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.

random.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.

Iv. Distribution of Truth value

The function of the top end of the random module is actually here.

random.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.

random.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

random.vonmisesvariate(mu, kappa)
Kappa distribution

random.paretovariate(alpha)
Pareto distribution

random.weibullvariate(alpha, beta)

V. Selectable generators

class random.SystemRandom([seed])
Use the Os.urandom () method to generate a random number of classes, provided by the operating system source code, not necessarily all systems support

Vi. Typical examples

>>> Random floating point number: 0.0 <= x < 1.00.37444887175646646>>> uniform (2.5, 10.0) # random floating point: 2.5 <= x < 10.03.1800146073117523>>> randrange (10) # 0-9 integer:7>>> randrange ( 0, 101, 2) # 0-100 even 26>>> choice ([' Win ', ' lose ', ' draw ') # randomly select an element from the sequence ' draw ' >>> deck = ' Ace Three four '. Split () >>> Shuffle (deck) # Shuffle the sequence, change the original sequence >>> deck[' four ', ' pair ', ' Ace ', ' three ']>>> sample ([Ten, Three, three, +], k=4) # does not change the original sequence to extract the specified number of samples and generates a new sequence [6, ten, Five, 30]>>> # rotation red Black green * (with weights repeatable fetch sample), without destroying the original sequence >>> 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 the 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) &GT;>> 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.>>> trial = lambda:choices (' HT ', cum_weights= (0.60, 1.00), k=7). Count (' H ') >= 5>>> s Um (Trial () for I in range (10000))/100000.4169>>> # Probability of the median of 5 samples being in Middle II Q uartiles>>> trial = lambda:2500 <= sorted (choices (range (10000), k=5)) [2] < 7500>>> sum (trial () F or I in range (10000))/100000.7958

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

Import random Checkcode = ' For I in range (4): Current  = Random.randrange (0,4) if current! =  I:    temp = Chr (ran Dom.randint (65,90))  else:    temp = random.randint (0,9)  Checkcode + = str (temp) print (Checkcode)

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

#!/usr/bin/env python#-*-coding:utf-8-*-import random, stringdef gen_random_string (length):  # Number of numbers randomly generated  num _of_numeric = Random.randint (1,length-1)  # All That's left is the alphabet  num_of_letter = length-num_of_numeric  # randomly generated numbers  Numerics = [Random.choice (string.digits) for I in Range (num_of_numeric)]  # randomly generates letters  letters = [Random.choice ( String.ascii_letters) for I in Range (Num_of_letter)]  # combine both  All_chars = numerics + Letters  # Shuffle  random . Shuffle (All_chars)  # generates the final string  result = '. Join ([I for I in All_chars])  return resultif __name__ = = ' __main __ ':  print (gen_random_string (64))

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.