search
HomeBackend DevelopmentPython TutorialAnalysis of random module in Python (with examples)

The content of this article is about the analysis of the random module in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor