search
HomeBackend DevelopmentPHP TutorialDetailed explanation of Python's random module

Detailed explanation of Python's random module

Dec 13, 2017 am 09:04 AM
pythonrandomDetailed explanation

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

3. Methods for sequence class structures<br>

random. choice(seq)Randomly select an element from the non-empty sequence seq. If seq is empty, an IndexError exception will pop up. <br>

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

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

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

4. True value distribution<br>

The most high-end function of the random module is actually here.

random.random()Returns a floating point number between left closed and right open [0.0, 1.0)<br>

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

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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