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!

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
