旺仔牛奶民族罐每箱12罐,假设在完全随机的情况下,计算买多少箱抽到56个不同民族的几率各有多少
1、list处理,计算结果用到list去重并计算个数
2、Python连接数据库,用于存储试验数据
3、为了缩短计算时间,用进程池的方式,多进程运算
4、random随机选取
建表
drop table if exists practice.wangzai_mz;
create table practice.wangzai_mz(
buy_num bigint
,buy_cnt bigint
,mz_type bigint
,create_time datetime
)
all_type=[
'A1','A2','A3','A4','A5','A6','A7','A8',
'A9','A10','A11','A12','A13','A14','A15','A16',
'A17','A18','A19','A20','A21','A22','A23','A24',
'A25','A26','A27','A28','A29','A30','A31','A32',
'A33','A34','A35','A36','A37','A38','A39','A40',
'A41','A42','A43','A44','A45','A46','A47','A48',
'A49','A50','A51','A52','A53','A54','A55','A56',
]
#先直接用号码代替了
engine = sqlalchemy.create_engine('数据库信息')
con=engine.connect()
def save_data(buy_num,mz_type):
in_sql='insert into practice.wangzai_mz values('+str(buy_num)+','+str(buy_num*12)+','+str(mz_type)+',"'+str(datetime.datetime.now())+'")'
in_sql = sqlalchemy.text(in_sql)
try:
con.execute(in_sql)
con.commit()
except:
print('执行失败')
print(in_sql)
def buy(x):
get_type=[]
for i in range(x):
for j in range(12):
get_type.append(random.choice(all_type))
type_cnt=set(get_type)
save_data(x, len(type_cnt))
return len(type_cnt)
if __name__=='__main__':
for i in range(5,24):
p = Pool(10)
for j in range(1000000):
p.apply_async(buy, args=(i,))
p.close()
p.join()
1、进程池进程数量:用的笔记本电脑性能不很高,设置过20就很卡了,如果电脑支持,可以设置的高一些
2、SQL执行的commit可以每100或者更多句再一起确定执行,但是担心sql有问题,就每句每执行了。