python加四位随机数_python生成四位随机数

1 #random.sample

2

3 defsample(self, population, k):4 """Chooses k unique random elements from a population sequence or set.5

6 Returns a new list containing elements from the population while7 leaving the original population unchanged. The resulting list is8 in selection order so that all sub-slices will also be valid random9 samples. This allows raffle winners (the sample) to be partitioned10 into grand prize and second place winners (the subslices).11

12 Members of the population need not be hashable or unique. If the13 population contains repeats, then each occurrence is a possible14 selection in the sample.15

16 To choose a sample in a range of integers, use range as an argument.17 This is especially fast and space efficient for sampling from a18 large population: sample(range(10000000), 60)19 """

20

21 #Sampling without replacement entails tracking either potential

22 #selections (the pool) in a list or previous selections in a set.

23

24 #When the number of selections is small compared to the

25 #population, then tracking selections is efficient, requiring

26 #only a small set and an occasional reselection. For

27 #a larger number of selections, the pool tracking method is

28 #preferred since the list takes less space than the

29 #set and it doesn‘t suffer from frequent reselections.

30

31 ifisinstance(population, _Set):32 population =tuple(population)33 if notisinstance(population, _Sequence):34 raise TypeError("Population must be a sequence or set. For dicts, use list(d).")35 randbelow =self._randbelow36 n =len(population)37 if not 0 <= k <=n:38 raise ValueError("Sample larger than population or is negative")39 result = [None] *k40 setsize = 21 #size of a small set minus size of an empty list

41 if k > 5:42 setsize += 4 ** _ceil(_log(k * 3, 4)) #table size for big sets

43 if n <=setsize:44 #An n-length list is smaller than a k-length set

45 pool =list(population)46 for i in range(k): #invariant: non-selected at [0,n-i)

47 j = randbelow(n-i)48 result[i] =pool[j]49 pool[j] = pool[n-i-1] #move non-selected item into vacancy

50 else:51 selected =set()52 selected_add =selected.add53 for i inrange(k):54 j =randbelow(n)55 while j inselected:56 j =randbelow(n)57 selected_add(j)58 result[i] =population[j]59 return result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值