Analysis of random module in Python (with examples)
random is a module for Python to generate pseudo-random numbers. The random seed defaults to the system clock. The methods in the module are analyzed below:
1. random.randint(start,stop)
This is a function that generates integer random numbers. The parameter start represents the minimum value, and the parameter stop represents the maximum value. , the values at both ends can be obtained;
The time complexity of the function algorithm is: O(1)
Core source code:
return self.randrange(a,b+1) #调用randrange函数来处理
Example:
import random for i in range(20): print(random.randint(0,10),end=' ')
Result:
1 1 7 5 10 1 4 1 0 8 7 7 2 10 6 8 6 0 3 1
2. random.randrange(start,stop,step)
is also a random integer function with optional parameters
Only When there is one parameter, the default random range is from 0 to this parameter, closed first and open later;
When there are two parameters, it represents the minimum and maximum values, closed first and open later
When there are three parameters, it represents the minimum value, maximum value and step size, closed first and open later
Time complexity of function algorithm: O(1)
Core source code:
return istart+istep*self._randbelow(n) #调用randbelow函数处理
Instance:
import random for i in range(10): print(random.randrange(10),end=' ') #产生0到10(不包括10)的随机数 print("") for i in range(10): print(random.randrange(5,10),end=' ') #产生5到10(不包括10)的随机数 print("") for i in range(10): print(random.randrange(5,100,5),end=' ') #产生5到100(不包括100)范围内的5倍整数的随机数
Result:
1 1 2 4 4 3 4 6 1 4 6 6 5 7 8 9 6 6 6 5 30 50 20 40 75 85 25 65 80 95
3.random.choice(seq)
A random Selection function, seq is a non-empty set, randomly selects an element in the set for output, and the type of element is not limited.
Core source code:
i=self._randbelow(len(seq)) #由randbelow函数得到随机地下标 return seq[i]
Function algorithm time responsibility: O(1)
Example:
import random list3=["mark","帅",18,[183,138]] for j in range(10): print(random.choice(list3),end=' ')
Code:
mark 帅 [183, 138] 18 mark 18 mark 帅 帅 [183, 138]
4. random.random()
This function forms any floating point number from 0.0 to 1.0, closed on the left and open on the right, with no parameters.
Example:
import random for j in range(5): print(random.random(),end=' ')
Run result:
0.357486615834809 0.5928029747238529 0.37053940107869987 0.3802224543848519 0.9741990956161711
5.random.send(n=None)
One can initialize the random number generator function, n represents a random seed; when n=None, the random seed is the system time. When n is other data, such as int, str, etc., the provided data is used as the random seed. The random number sequence generated at this time is fixed. .
Example:
import random random.seed("mark") for j in range(20):#无论启动多少次程序,输出的序列不变 print(random.randint(0,10),end=' ')
Result:
4 1 10 5 6 2 8 5 5 10 7 2 9 6 2 6 0 5 10 10
6.random.getstate() and random.setstate(state):
getstate() function is used To record the state of the random number generator, the setstate(state) function is used to restore the generator to the last recorded state.
Example:
import random tuple1=random.getstate()#记录生成器的状态 for i in range(20): print(random.randint(0,10),end=' ') print() random.setstate(tuple1)#传入参数回复之间的状态 for i in range(20): print(random.randint(0,10),end=' ')#两次输出的结果一致
Result:
5 7 9 9 10 10 2 3 7 1 1 6 1 7 1 1 7 4 2 2 5 7 9 9 10 10 2 3 7 1 1 6 1 7 1 1 7 4 2 2
7.random.shuffle(seq,random=None):
Shuffle the incoming collection sequence operation. It can only be used for mutable sequences, such as strings and lists. An error will be reported for immutable sequences such as tuples. random is used to select the out-of-order operation method, such as random=random.
Core source code:
for i in reversed(range(1,len(x))): j=randbelow(i+1) x[i],x[j]=x[k],x[i]
Time complexity of function algorithm: O(n)
Example:
import random lists=['mark','帅哥',18,[183,138]] print(lists) random.shuffle(lists,random=None) print(lists)
Result:
['mark', '帅哥', 18, [183, 138]] ['帅哥', 18, 'mark', [183, 138]]
8. random.sample(population,k):
The population parameter is a sequence, such as a list, tuple, set, string, etc.; k elements are randomly selected from the set to form a new sequence, The original sequence will not be changed.
Worst time complexity: O(n*n)
Example:
import random lists=['mark','帅哥',18,[183,138]] lists2=random.sample(lists,3) print(lists) print(lists2)
Result:
['mark', '帅哥', 18, [183, 138]] ['mark', [183, 138], '帅哥']
9, random.uniform(a, b)
A function that generates a floating-point number between parameters a and b. If a>b, it generates a floating-point number between b and a.
Core source code:
return a+(b-a)*self.random()
Time complexity: 0(1)
Example:
import random for i in range(5): print(random.uniform(10,1))
Result:
2.8826090956524606 1.5211191352548408 3.2397454278562794 4.147879756524251 6.532545391009419
The above is the detailed content of Analysis of random module in Python (with examples). 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

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

Convert XML to PDF with high quality on your mobile phone requires: parsing XML in the cloud and generating PDFs using a serverless computing platform. Choose efficient XML parser and PDF generation library. Handle errors correctly. Make full use of cloud computing power to avoid heavy tasks on your phone. Adjust complexity according to requirements, including processing complex XML structures, generating multi-page PDFs, and adding images. Print log information to help debug. Optimize performance, select efficient parsers and PDF libraries, and may use asynchronous programming or preprocessing XML data. Ensure good code quality and maintainability.

Converting XML to PDF directly on Android phones cannot be achieved through the built-in features. You need to save the country through the following steps: convert XML data to formats recognized by the PDF generator (such as text or HTML); convert HTML to PDF using HTML generation libraries such as Flying Saucer.
