双色球

该代码是随机生成双色球,并且保存到文件中,要求新产生的投注不能和文件中已保存的投注一样

# 1.红色球6个,1,33,蓝色球1个,1,16
# 2.先从1-33之间取6个   random.sample([1,33],6)
# 3.再从1-16之间取1个
# 4.把双色球号码改成   红色球 03 08 14 25 28 32 蓝色球 05   的格式
# 5.读取文件内容     判断产生的数据是否在文件中
# 6.不在就写入

import random

FILENAME = 'ball.txt'

def op_file(content=None):
    with open(FILENAME,'a+',encoding='utf-8') as fw:
        if content:
            fw.write(content)
        else:
            fw.seek(0)
            return fw.read()


def seq(num):
    count = 0
    while count<num:
        red = random.sample([ str(i).zfill(2) for i in range(1,34)],6)     #返回的是list
        red.sort()
        blue = random.choice([ str(i).zfill(2) for i in range(1,17)])
        red_str = ' '.join(red)     #‘01 02 03 04 05 06’
        resault = "红色球 %s 蓝色球 %s\n"%(red_str,blue)
        all_ball = op_file()
        if resault not in all_ball:
            op_file(resault)
            count+=1

可以改写成下面更简单的方式:

# 1.红色球6个,1,33,蓝色球1个,1,16
# 2.先从1-33之间取6个   random.sample([1,33],6)
# 3.再从1-16之间取1个
# 4.把双色球号码改成   红色球 03 08 14 25 28 32 蓝色球 05   的格式
# 5.读取文件内容     判断产生的数据是否在文件中
# 6.不在就写入

import random

FILENAME = 'ball.txt'

def op_file(content=None):
    with open(FILENAME,'a+',encoding='utf-8') as fw:
        if content:
            fw.write(content)
        else:
            fw.seek(0)
            return fw.read()


def seq(num):
    count = 0
    while count<num:
        red =' '.join(sorted(random.sample([ str(i).zfill(2) for i in range(1,34)],6)))      #返回的是list
        blue = random.choice([ str(i).zfill(2) for i in range(1,17)])
        resault = "红色球 %s 蓝色球 %s\n"%(red,blue)
        if resault not in op_file():
            op_file(resault)
            count+=1

posted @ 2019-04-28 14:26  狂爷  阅读(161)  评论(0编辑  收藏  举报