python生成四位随机数
有些时候需要发送短信给用户生成四位随机数字,这里在python中我们可以根据python自带的标准库random和string来实现。
- random下有三个可以随机取数的函数,分别是choice,choices,sample
# random.choice
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
try:
i = self._randbelow(len(seq))
except ValueError:
raise IndexError('Cannot choose from an empty sequence') from None
return seq[i]
# random.choices
def choices(self, population, weights=None, *, cum_weights=None, k=1):
"""Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified,
the selections are made with equal probability. """
random = self.random
if cum_weights is None:
if weights is None:
_int = int
total = len(population)
return [population[_int(random() * total)] for i in range(k)]
cum_weights = list(_itertools.accumulate(weights))
elif weights is not None:
raise TypeError('Cannot specify both weights and cumulative weights')
if len(cum_weights) != len(population):
raise ValueError('The number of weights does not match the population')
bisect = _bisect.bisect
total = cum_weights[-1]
hi = len(cum_weights) - 1
return [population[bisect(cum_weights, random() * total, 0, hi)]
for i in range(k)]
# random.sample def sample(self, population, k):
"""Chooses k unique random elements from a population sequence or set. Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample. To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(range(10000000), 60)
""" # Sampling without replacement entails tracking either potential
# selections (the pool) in a list or previous selections in a set. # When the number of selections is small compared to the
# population, then tracking selections is efficient, requiring
# only a small set and an occasional reselection. For
# a larger number of selections, the pool tracking method is
# preferred since the list takes less space than the
# set and it doesn't suffer from frequent reselections. if isinstance(population, _Set):
population = tuple(population)
if not isinstance(population, _Sequence):
raise TypeError("Population must be a sequence or set. For dicts, use list(d).")
randbelow = self._randbelow
n = len(population)
if not 0 <= k <= n:
raise ValueError("Sample larger than population or is negative")
result = [None] * k
setsize = 21 # size of a small set minus size of an empty list
if k > 5:
setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
if n <= setsize:
# An n-length list is smaller than a k-length set
pool = list(population)
for i in range(k): # invariant: non-selected at [0,n-i)
j = randbelow(n-i)
result[i] = pool[j]
pool[j] = pool[n-i-1] # move non-selected item into vacancy
else:
selected = set()
selected_add = selected.add
for i in range(k):
j = randbelow(n)
while j in selected:
j = randbelow(n)
selected_add(j)
result[i] = population[j]
return result
从上面这三个函数看来,都可以在给定的一个数字集内随机产生四位数字。三种方法如下:
import string
import random # 方法一
seeds = string.digits
random_str = []
for i in range(4):
random_str.append(random.choice(seeds))
print("".join(random_str)) # 方法二
seeds = string.digits
random_str = random.choices(seeds, k=4)
print("".join(random_str)) # 方法三
seeds = string.digits
random_str = random.sample(seeds, k=4)
print("".join(random_str))
- 说明一下:string.digits是一个定义好的数字字符串,就是从"0123456789"。
"""
whitespace -- a string containing all ASCII whitespace
ascii_lowercase -- a string containing all ASCII lowercase letters
ascii_uppercase -- a string containing all ASCII uppercase letters
ascii_letters -- a string containing all ASCII letters
digits -- a string containing all ASCII decimal digits
hexdigits -- a string containing all ASCII hexadecimal digits
octdigits -- a string containing all ASCII octal digits
punctuation -- a string containing all ASCII punctuation characters
printable -- a string containing all ASCII characters considered printable
""" # Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = ''
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = ''
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace
上述三种方式虽说都可以生成随机数,但是choice和choices随机取得数字是可重复的,而sample方法的随机数是不会重复的。这个是他们之间的区别之一。
python生成四位随机数的更多相关文章
- 生成四位随机数的PHP代码
纯数字的四位随机数 rand(1000,9999) 数字和字符混搭的四位随机字符串: function GetRandStr($len) { $chars = array( "a" ...
- js生成四位随机数的简便方法
do out = Math.floor(Math.random()*10000); while( out < 1000 ) alert( out );
- java生成四位随机数,包含数字和字母 区分大小写,特别适合做验证码,android开发
private String generateWord() { String[] beforeShuffle = new String[] { "2", "3" ...
- 【python】【转】Python生成随机数的方法
如果你对在Python生成随机数与random模块中最常用的几个函数的关系与不懂之处,下面的文章就是对Python生成随机数与random模块中最常用的几个函数的关系,希望你会有所收获,以下就是这篇文 ...
- Python生成随机数的方法
这篇文章主要介绍了Python生成随机数的方法,有需要的朋友可以参考一下 如果你对在Python生成随机数与random模块中最常用的几个函数的关系与不懂之处,下面的文章就是对Python生成随机数与 ...
- python生成随机数、随机字符串
python生成随机数.随机字符串 import randomimport string # 随机整数:print random.randint(1,50) # 随机选取0到100间的偶数:print ...
- [ Python入门教程 ] Python生成随机数模块(random)使用方法
1.使用randint(a,b)生成指定范围内的随机整数.randint(a,b)表示从序列range([a,b])中获取一个随机数,包括b. >>> random.randint( ...
- Python下探究随机数的产生原理和算法
资源下载 #本文PDF版下载 Python下探究随机数的产生原理和算法(或者单击我博客园右上角的github小标,找到lab102的W7目录下即可) #本文代码下载 几种随机数算法集合(和下文出现过的 ...
- 利用Python生成随机密码
#coding:utf-8 #利用python生成一个随机10位的字符串 import string import random import re list = list(string.lowerc ...
随机推荐
- web项目部署后动态编译无法找到依赖的jar包
很纳闷的一个问题,通过配置文件生成的java源码在本地动态编译没有问题,但是部署服务器后编译不通过,找不到依赖的jar包. 通过网上查资料,找到一个兄弟提供的方法,问题解决了:下面贴出代码以供参考: ...
- 在linux服务器下日志提取的python脚本(实现输入开始时间和结束时间打包该时间段内的文件)
1.需求:近期在提取linux服务器下的日志文件时总是需要人工去找某个时间段内的日志文件,很是枯燥乏味,于是乎,我就想着用python结合linux指令来写一个日志提取的脚本,于是就有了以下脚本文件: ...
- 【Sass初级】嵌套选择器规则
在CSS中,我们都知道所有代码都在一个“根级别”的选择器中,每个CSS的样式声明都写嵌套的话,那意客味需要写很多的代码. 今天我要带领大家进入到Sass的最基本原则中.这就是所谓的“基础规则(Ince ...
- MySql提示:The server quit without updating PID file(…)失败之解决办法(来源网络仅供参考)
1.可能是/usr/local/mysql/data/rekfan.pid文件没有写的权限 解决方法 :给予权限,执行 “chown -R mysql:mysql /var/data” “chmod ...
- 长春理工大学第十四届程序设计竞赛(重现赛)H.Arithmetic Sequence
题意: 数竞选手小r最喜欢做的题型是数列大题,并且每一道都能得到满分. 你可能不相信,但其实他发现了一个结论:只要是数列,无论是给了通项还是给了递推式,无论定义多复杂,都可以被搞成等差数列.这样,只要 ...
- 前端JavaScript(2) --常用内置对象,函数,伪数组 arguments,关于DOM的事件操作,DOM介绍
昨日内容回顾 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 ...
- 解决lnmp无法远程登录的bug
使用lnmp一键安装好linux环境后,不能远程连接到所在服务器的mysql,但是通过80端口可以登录phpmyadmin,发现原来是因为lnmp的大多数版本为了安全不禁止远程连接mysql,方法很简 ...
- 将JWT与Spring Security OAuth结合使用
1.概述 在本教程中,我们将讨论如何使用Spring Security OAuth2实现来使用JSON Web令牌. 我们还将继续构建此OAuth系列的上一篇文章. 2. Maven配置 首先,我们需 ...
- Java选择排序算法
package com.jckb; /**选择排序 * * @author gx *算法原理: *第一个数和后面每个数进行比较,如果大于后面的数就进行位置交换, *第一次比较结束后得到了最小值 */ ...
- VS连接Access数据库--连接字符串及执行查询语句的方法(增删改查,用户名查重,根据用户获取密码查询)
ACCESS数据的连接及语句执行操作,不难,久不用会生疏,每次都要找资料,干脆自己整理下,记录下来,需要的时候,直接查看,提高效率.也供初学者参考 1.连接字符串 public static stri ...