目录:
目的:理解random.seed(),通过代码探究并验证其功能。
趣味思考:例如 random.seed(43)时
探究:固定seed下对含任意数量(>1)元素的列表进行任意深度的shuffle排序测试:
背景:random()是伪随机,实际上由确定公式根据初始值seed计算得出。
当seed固定时,对特定数据的处理会产生相同的结果。
试探究固定seed下random.shuffle()对字符串列表排序的影响:
对三元素列表使用random.shuffle,结果为:[a, b, c] → [c, b, a]
you are superman → superman are you (与list.reverse()效果相同)
对四元素列表使用random.shuffle,结果为:[a, b, c, d] → [c, d, b, a]
I am the king → the king I am
import random
sentence = input().split()
random.seed(43)
random.shuffle(sentence)
print(' '.join(sentence))
以seed取值1-9为例(实际可为任意值):
import random
import numpy as np
size = int(input("size:"))
depth = int(input("depth:"))
for i in range(1, 10): # 可修改为任意正整数区间
ls = []
for j in range(depth):
seq = [chr(p) for p in range(97, 97 + size)]
random.seed(i)
random.shuffle(seq)
sentence = '_'.join(seq)
ls.append(sentence)
# print(j,sentence)
b, s = np.unique(ls, return_counts=True)
# c = [rv for r in zip(b, s) for rv in r]
print('seed:{} clear in {} repeated {} times'.format(i, b, s))
exit(0)
例:
input: size: 4 depth: 100
output:
seed:1 clear in ['d_a_c_b'] repeated [100] times
seed:2 clear in ['b_c_d_a'] repeated [100] times
seed:3 clear in ['d_a_c_b'] repeated [100] times
seed:4 clear in ['c_a_d_b'] repeated [100] times
seed:5 clear in ['a_b_d_c'] repeated [100] times
seed:6 clear in ['d_c_b_a'] repeated [100] times
seed:7 clear in ['d_b_a_c'] repeated [100] times
seed:8 clear in ['a_c_d_b'] repeated [100] times
seed:9 clear in ['a_b_c_d'] repeated [100] times
应用:在操作对字符串列表进行特定顺序重组时:
通过利用以上代码,尝试查询固定seed下的shuffle结果
(运气好的话)可以实现对特定排序的快速应用,省去部分逻辑排序代码的编写。