Home>Article>Backend Development> Detailed explanation of Python's random module

Detailed explanation of Python's random module

小云云
小云云 Original
2017-12-13 09:04:21 2806browse

This article mainly introduces the relevant content of Python's random module, which has certain reference value. Friends who need it can refer to it. I hope it can help everyone.

random module

is used to generate pseudo-random numbers

Truly random numbers (or random events) are randomly generated in a certain generation process according to the distribution probability shown in the experimental process, and the results are unpredictable and invisible. The random function in the computer is simulated according to a certain algorithm, and the result is certain and visible. We can assume that the probability of this foreseeable outcome is 100%. Therefore, the "random numbers" generated by the computer random function are not random, but pseudo-random numbers.

The pseudo-random number of the computer is a value calculated by a random seed according to a certain calculation method. Therefore, as long as the calculation method is certain and the random seed is certain, the random numbers generated are fixed.

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

This library of Python uses a common algorithm at the bottom. After long-term testing, its reliability cannot be said, but it must not be used for password-related functions.

1. Basic method

random.seed(a=None, version=2)
Initialize the pseudo-random number generator. If a is not provided or a=None, the system time is used as the seed. If a is an integer, it is used as the seed.

random.getstate()
Returns an object of the internal state of the current generator

random.setstate(state)
Pass in a state object previously obtained using the getstate method to restore the generator to this state.

random.getrandbits(k)
Returns a Python integer (decimal) not larger than K bits. For example, k=10, the result is between 0~2^10 Integer.

2. Methods for integers

##random.randrange(stop)

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

random.randint(a, b)Returns a random integer N where a b0e2df88c81c22b68aa55687803d59bbb, it is a floating point number between b and a. Both a and b here may appear in the result.

random.triangular(low, high, mode)Returns a random number from a triangular distribution with low <= N <=high. The mode parameter specifies the position where the mode appears.

random.betavariate(alpha, beta)Beta distribution. The returned result is between 0 and 1

random.expovariate(lambd)Exponential distribution

random.gammavariate(alpha, beta)Gamma distribution

random.gauss(mu, sigma)
Gaussian distribution

random.lognormvariate(mu, sigma)Lognormal distribution

random.normalvariate(mu, sigma)Normal distribution

random.vonmisesvariate( mu, kappa)Kappa distribution

random.paretovariate(alpha)
Pareto distribution

random.weibullvariate (alpha, beta)

5. Optional generator

class random.SystemRandom( [seed])Use the os.urandom() method to generate random numbers. The source code is provided by the operating system. Not all systems may support it

6. Typical example of

>>> random() # 随机浮点数: 0.0 <= x < 1.0 0.37444887175646646 >>> uniform(2.5, 10.0) # 随机浮点数: 2.5 <= x < 10.0 3.1800146073117523 >>> randrange(10) # 0-9的整数: 7 >>> randrange(0, 101, 2) # 0-100的偶数 26 >>> choice(['win', 'lose', 'draw']) # 从序列随机选择一个元素 'draw' >>> deck = 'ace two three four'.split() >>> shuffle(deck) # 对序列进行洗牌,改变原序列 >>> deck ['four', 'two', 'ace', 'three'] >>> sample([10, 20, 30, 40, 50], k=4) # 不改变原序列的抽取指定数目样本,并生成新序列 [40, 10, 50, 30] >>> # 6次旋转红黑绿*(带权重可重复的取样),不破坏原序列 >>> choices(['red', 'black', 'green'], [18, 18, 2], k=6) ['red', 'green', 'black', 'black', 'red', 'black'] >>> # 德州扑克计算概率Deal 20 cards without replacement from a deck of 52 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') / 20 0.15 >>> # 模拟概率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 >>> sum(trial() for i in range(10000)) / 10000 0.4169 >>> # Probability of the median of 5 samples being in middle two quartiles >>> trial = lambda : 2500 <= sorted(choices(range(10000), k=5))[2] < 7500 >>> sum(trial() for i in range(10000)) / 10000 0.7958

The following is a program to generate a random 4-digit verification code containing the uppercase letters A-Z and the numbers 0-9

import random checkcode = '' for i in range(4): current = random.randrange(0,4) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += str(temp) print(checkcode)

The following is the code to generate a random sequence of letters and numbers of a specified length:

#!/usr/bin/env python # -*- coding:utf-8 -*- import random, string def gen_random_string(length): # 数字的个数随机产生 num_of_numeric = random.randint(1,length-1) # 剩下的都是字母 num_of_letter = length - num_of_numeric # 随机生成数字 numerics = [random.choice(string.digits) for i in range(num_of_numeric)] # 随机生成字母 letters = [random.choice(string.ascii_letters) for i in range(num_of_letter)] # 结合两者 all_chars = numerics + letters # 洗牌 random.shuffle(all_chars) # 生成最终字符串 result = ''.join([i for i in all_chars]) return result if __name__ == '__main__': print(gen_random_string(64))

Related recommendations:

Python implementation of strings Matching algorithm example code

Comparison of similarities and differences between Python and ruby

Summary of the use of logging libraries in python

The above is the detailed content of Detailed explanation of Python's random module. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn