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

Detailed explanation of Python's random module

小云云
小云云Original
2017-12-13 09:04:212830browse

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<br>

is used to generate pseudo-random numbers<br>

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

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

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<br>

random.seed(a=None, version=2)<br>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()<br>Returns an object of the internal state of the current generator

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

random.getrandbits(k)<br>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<br>

##random.randrange(stop)<br>

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

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

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

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

random.expovariate(lambd)Exponential distribution<br>

random.gammavariate(alpha, beta)Gamma distribution<br>

random.gauss(mu, sigma)<br>Gaussian distribution

random.lognormvariate(mu, sigma) Lognormal distribution<br>

random.normalvariate(mu, sigma)Normal distribution<br>

random.vonmisesvariate( mu, kappa)Kappa distribution<br>

random.paretovariate(alpha)<br>Pareto distribution

random.weibullvariate (alpha, beta)

5. Optional generator<br>

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<br>

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([&#39;win&#39;, &#39;lose&#39;, &#39;draw&#39;])   # 从序列随机选择一个元素
&#39;draw&#39;

>>> deck = &#39;ace two three four&#39;.split()
>>> shuffle(deck)            # 对序列进行洗牌,改变原序列
>>> deck
[&#39;four&#39;, &#39;two&#39;, &#39;ace&#39;, &#39;three&#39;]

>>> sample([10, 20, 30, 40, 50], k=4)  # 不改变原序列的抽取指定数目样本,并生成新序列
[40, 10, 50, 30]

>>> # 6次旋转红黑绿*(带权重可重复的取样),不破坏原序列
>>> choices([&#39;red&#39;, &#39;black&#39;, &#39;green&#39;], [18, 18, 2], k=6)
[&#39;red&#39;, &#39;green&#39;, &#39;black&#39;, &#39;black&#39;, &#39;red&#39;, &#39;black&#39;]

>>> # 德州扑克计算概率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(&#39;tens&#39;) / 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(&#39;HT&#39;, cum_weights=(0.60, 1.00), k=7).count(&#39;H&#39;) >= 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 = &#39;&#39;
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 = &#39;&#39;.join([i for i in all_chars])
  return result

if __name__ == &#39;__main__&#39;:
  print(gen_random_string(64))

Related recommendations: <br>

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