2019-06-24 使用random生成抽奖数组

看了随机数的函数挺有意思,正好参加学校的Summer Fair,看到很多抽奖的,就是很多小纸条上面印的数字,末尾数是5或0的中奖,或者特殊数字中奖的那种。正好用python写个脚本来生成抽奖数组。
要求:
随机生成100个3位数字,要求其中有20个尾数是0或5的作为中奖数字。
直接上脚本:

#!/usr/bin/env python3
import random
def rad1():    #定义生成3位随机数的函数
    a = ''.join(str(random.choice(range(10))) for _ in range(3))
    return(a)

list1 = []
c1 = 0
counter = 1
s = 0
while counter <= 100:
    b = rad1()
    if b[2] in ('5','0'):  #检查尾数是否0或5
        if c1 < 20:     #有没有20个尾数0或5的数字,没有就写进列表
            list1.append(b)
            c1 +=1
            counter +=1
            print('The ' + str('{:>2}'.format(c1)) + ' win number is ' + b)
        elif c1 >=20:  #已经有20个了,pass
            pass
    elif b[2] not in ('5','0'):  #尾数不是0或5的,写进列表
        if c1 >= 20:
            if b not in list1:  #避免重复数字
                list1.append(b)
                counter +=1
random.shuffle(list1)  #洗牌,数组生成的时候中奖数字都在前面
print(c1, len(list1),list1)

看下输出:

The  1 win number is 740
The  2 win number is 115
The  3 win number is 030
The  4 win number is 260
The  5 win number is 020
The  6 win number is 780
The  7 win number is 255
The  8 win number is 500
The  9 win number is 725
The 10 win number is 555
The 11 win number is 560
The 12 win number is 600
The 13 win number is 570
The 14 win number is 580
The 15 win number is 420
The 16 win number is 885
The 17 win number is 725
The 18 win number is 560
The 19 win number is 635
The 20 win number is 015
20 100 ['433', '788', '146', '142', '833', '728', '811', '336', '287', '362', '282', '327', '412', '635', '182', '626', '376', '507', '802', '780', '763', '570', '818', '366', '576', '608', '503', '341', '260', '501', '264', '613', '020', '704', '278', '740', '652', '317', '244', '658', '030', '500', '462', '258', '428', '420', '560', '776', '057', '424', '152', '434', '138', '831', '443', '177', '221', '872', '555', '333', '115', '083', '255', '343', '560', '468', '580', '218', '176', '361', '512', '548', '725', '247', '403', '386', '682', '636', '582', '741', '044', '301', '887', '516', '482', '483', '003', '747', '353', '600', '143', '657', '015', '141', '725', '457', '748', '051', '242', '885']

你可能感兴趣的:(2019-06-24 使用random生成抽奖数组)