Article directory
foreword
- About the author: High-quality creators and data development engineers in the field of Python
- Inspirational to become a Python full-stack engineer, follow me to find more exciting~
- This article has been included in the Python full stack series: 100 days to master Python from entry to employment
- Welcome to subscribe, after subscribing to the column, you can privately chat into the 100-person Python full-stack communication group (hand-to-hand teaching, question answering); you can also receive 80GPython full-stack tutorial + 300 computer books : basics, web, crawler, data analysis, visualization, machine learning , deep learning, artificial intelligence, algorithms, interview questions, etc.
- Join me to learn and progress together, a person can go fast, a group of people can go further!
1. Introduction to random library
伪随机数
The random module implements generators for various distributions . Why is it called pseudo-random number: that is, humans use algorithms and other methods to construct a series of numbers based on a benchmark (also called a seed, the most commonly used is a timestamp), and the characteristics of these numbers conform to what people understand as random numbers. However, because it is obtained through an algorithm, once the algorithm and the seed are determined, the sequence of random numbers generated is also determined, so it is called a pseudo-random number.
import random
2. Common functions
random.seed(a)
Set the initial random seed, which can output the same random number sequence; a is an integer or a floating point number, if not set, the system time is used as the seed by default
import random
print("没有设定种子时")
for i in range(5):
ret = random.randint(1, 10)
print(ret, end=" ")
print()
print("设定种子时")
random.seed(1)
for i in range(5):
ret = random.randint(1, 10)
print(ret, end=" ")
Output result:
As can be seen from the above figure: when the seed is not explicitly set, the random number output each time is different; when the seed is explicitly set, the random number output each time is the same
random.random()
Used to generate a random floating point number from 0.0 to 1.0
>>> import random
>>> random.random()
0.9279749775408933
>>> random.random()
0.12720379394341363
>>> random.random()
0.9391670189485866
random.uniform(a,b)
Generate a
[a,b]
random decimal between a and b; integer or float
>>> import random
>>> random.uniform(10.0, 20.0)
10.839441969258752
>>> random.uniform(10.0, 20.0)
12.233491150445115
>>> random.uniform(10, 20)
11.290566243261305
random.randint(a,b)
generate a
[a,b]
random integer between
>>> import random
>>> random.randint(10,100)
100
>>> random.randint(10,100)
83
>>> random.randint(10,100)
66
random.randrange (start, stop, [step])
Generate a
[start,stop)
random integer with step as the number of steps; start, stop, step are integers, and the default value is 1 when step is not set
Randomly generate integers from 1-100:
>>> import random
>>> random.randrange(1,100)
54
>>> random.randrange(1,100)
21
>>> random.randrange(1,100)
71
Randomly generate odd numbers from 1-100:
>>> import random
>>> random.randrange(1,100,2)
37
>>> random.randrange(1,100,2)
63
>>> random.randrange(1,100,2)
29
Randomly generate even numbers from 1-100:
>>> import random
>>> random.randrange(2,100,2)
62
>>> random.randrange(2,100,2)
6
>>> random.randrange(2,100,2)
46
random.getrandbits(k)
Generate a
占内存k位
random integer within one; k takes an integer value of length
>>> import random
>>> random.getrandbits(10)
29
>>> random.getrandbits(10)
540
>>> random.getrandbits(10)
227
random.choice(seq)
Returns an element randomly from the sequence type seq; seq takes the sequence type: such as string, list, tuple
>>> import random
>>> list = ['a', 'b', 'c', 'd', 'f', 'g']
>>> random.choice(list)
'b'
>>> random.choice(list)
'f'
>>> random.choice(list)
'g'
random.shuffle(seq)
Randomly sort the elements in the sequence type, return the scrambled sequence, seq is changed (
改变原列表
), shuffle means shuffle; seq takes the sequence type: such as string, list, tuple
>>> import random
>>> list = ['a', 'b', 'c', 'd', 'f', 'g']
>>> random.shuffle(list)
>>> list
['c', 'a', 'f', 'd', 'g', 'b']
>>> random.shuffle(list)
>>> list
['f', 'a', 'b', 'c', 'g', 'd']
>>> random.shuffle(list)
>>> list
['a', 'd', 'g', 'c', 'b', 'f']
random.sample(pop,k)
Select k elements from pop and return it as a list type (
不改变原列表
); pop is a sequence type, and k is an integer: it represents the number of selected items
>>> import random
>>> list = ['a', 'b', 'c', 'd', 'f', 'g']
>>> random.sample(list, 4)
['b', 'f', 'c', 'a']
>>> random.sample(list, 4)
['g', 'f', 'b', 'd']
>>> random.sample(list, 4)
['g', 'f', 'c', 'b']
3. Uncommon functions
random.getstate()
An object that captures and returns the generator's current internal state, which can be passed to the setstate() function to restore the generator's internal state to the state it was in before the getstate() function was called. Equivalent to backup.
random.setstate(state)
state should be the result of the getstate() function, which is used to restore the current internal state of the generator to state.
random.betavariate(alpha, beta)
Beta distribution: The parameters are conditioned on alpha > 0 and beta > 0, and the returned value ranges between 0 and 1.
random.expovariate(lambd)
index distribution
random.gammavariate(alpha, beta)
Gamma distribution: parameters are conditional on alpha > 0 and beta > 0
random.gauss(mu, sigma)
Gaussian distribution: mu is the mean and sigma is the standard deviation.
random.normalvariate(mu, sigma)
Normal distribution: mu is the mean and sigma is the standard deviation.
random.paretovariate(alpha)
Pareto distribution: alpha is the shape parameter.
random.weibullvariate(alpha,beta)
Weibull distribution: alpha is the scale parameter and beta is the shape parameter.
4. Real cases
random password string
The string includes numbers and letters, and the number of digits in the password can be specified
import random
import string
def get_random_string(length):
# 随机生成字母和数字的位数
num_count = random.randint(1, length - 1)
letter_count = length - num_count
# 随机抽样生成数字序列
num_list = [random.choice(string.digits) for _ in range(num_count)]
# 随机抽样生成字母序列
letter_list = [random.choice(string.ascii_letters) for _ in range(letter_count)]
# 合并字母和数字
all_list = num_list + letter_list
# 乱序
random.shuffle(all_list)
result = "".join([i for i in all_list])
return result
# 生成10位的密码
password1 = get_random_string(10)
print(password1)
# 生成15位的密码
password2 = get_random_string(15)
print(password2)
# 生成20位的密码
password3 = get_random_string(20)
print(password3)
Output result:
41eD76F3e1
915087432k8443z
002L5292840A07284755
Calculate pi
1) Approximate formula for calculating pi:
pi = 0
N = 100
for k in range(N):
pi += 1 / pow(16, k) * (4 / (8 * k + 1) - 2 / (8 * k + 4) - 1 / (8 * k + 5) - 1 / (8 * k + 6))
print("圆周率值是:%s" % pi)
Output result:
圆周率值是: 3.141592653589793
2) Monte Carlo algorithm:
import random
DARTS = 1000 * 1000 * 10
hits = 0.0
for i in range(1, DARTS + 1):
x, y = random.random(), random.random()
dist = pow(x ** 2 + y ** 2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits / DARTS)
print("圆周率值是:%s" % pi)
Output result:
圆周率值是:3.14205