python : 蒙特卡罗算法 应用于双色球

来源:互联网 发布:spark als推荐算法 编辑:程序博客网 时间:2024/05/19 23:19

参考书:算法设计与分析 王晓东 编著 :第7章 概率算法 7.5 蒙特卡罗算法 

http://www.gdfc.org.cn/datas/history/twocolorball/history_1.html 抓取双色球开奖数据

2017001,09,11,14,20,25,26,15
2017002,15,19,23,24,25,32,03
2017003,01,04,08,15,27,32,16

 ... ...

存为数据文件: cp2017.txt

自设seed种子,随机生成1注6个红球,计算这1组数字与双色球开奖历史数据之相似性。

redball.py

# -*- coding: cp936 -*-import os, sysimport random# 计算红球相似性if len( sys.argv ) ==2:    p1 = long(sys.argv[1])else:    print 'usage: redball.py seed_int '    sys.exit(1)f1 = "cp2017.txt"if not os.path.exists(f1):    print 'ERROR: %s is not found.' % f1    sys.exit(1)def mc(A , B):    k=0    for a in A:        if a in B:            k +=1    return k#A = [ 0 for i in range(0,7)] # 初始化一个具有6个0的数组,# 随机选出6个红球random.seed(p1)reds = [] while len(reds) < 6:    N = random.randint(1,33)    if N not in reds:        reds.append(N)print 'random:',sorted(reds)fp = open(f1,'r')        alist =[] ln =0for line in fp:    alist = line.strip().split(',')    for i in range(1,7):        A[i] = int(alist[i])    k = mc(reds, A[1:])    if k > 3:        ln += 1        print line.rstrip(),':',k#fp.close()print 'ln=',ln

例如: 执行 redball.py  1254436

random: [4, 10, 11, 25, 30, 31]

2017115,04,10,11,25,30,31,01 : 6




阅读全文
0 0
原创粉丝点击