Detailed explanation of Python's random module
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 <= N <= b. Equivalent to randrange(a, b+1)
3. Methods for sequence class structures
random. choice(seq)Randomly select an element from the non-empty sequence seq. If seq is empty, an IndexError exception will pop up.
random.choices(population, weights=None, *, cum_weights=None, k=1)New in version 3.6. K elements are randomly selected from the population cluster. Weights is a relative weight list, cum_weights is the cumulative weight, and the two parameters cannot exist at the same time.
random.shuffle(x[, random])Randomly shuffle the order of elements in sequence x. It can only be used for mutable sequences. For immutable sequences, please use the sample() method below.
random.sample(population, k) Randomly extract K non-repeating elements from the population sample or set to form a new sequence. Often used for random sampling without repetition. What is returned is a new sequence without destroying the original sequence. To randomly draw a certain number of integers from an integer range, use a method like sample(range(10000000), k=60), which is very efficient and space-saving. If k is greater than the length of population, a ValueError exception will pop up.
4. True value distribution
random.random()Returns a floating point number between left closed and right open [0.0, 1.0)
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 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(['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: <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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
