#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import random
import string
la=[0,1,2,3,4,5,6,7,8,9]
print(random.seed(10))
print(random.getrandbits(3))
#16位小数
re=print(random.random())
# 15位小数
re=print(random.uniform(0,9))
re=print(random.randrange(3))
re=print(random.randrange(0,9,1))
re=print(random.randint(0,9))
#随机选择一位元素 非空序列
re=print(random.choice(la))
re=print(random.choices(la,weights=None,cum_weights=2,k=3))
#生成k=3个元素组成的列表,根据权重去生成
print(random.choices([3,6,9], [2, 5, 7], k=3))
#
re=print(random.shuffle(['a','ff','cc','test']))
#生成新的序列 不重复 k为 元素个数
re=print(random.sample(la,k=5))
#根据生成的字符次数情况算概率
trial = lambda: random.choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
re=sum(trial() for i in range(10000)) / 10000
print(re)
trial = lambda : 2500 <= sorted(random.choices(range(10000), k=5))[2] < 7500
re=sum(trial() for i in range(10000)) / 10000
print(re)
#生成随机数包含大写字母+数字
checkcode = ''
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)
#指定生成位数的随机数 包含字母和数字
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 = ''.join([i for i in all_chars])
# result = ''.join(all_chars)
return result
if __name__ == '__main__':
print(gen_random_string(4))