Suddenly code
Bingo.py
# -*- coding: utf-8 -*-
u"""Script that simulates the probability of BINGO
input:
times =Number of times to turn the lottery machine, card_num =Number of cards
outpu:
Probability of getting even one
"""
import sys
from random import sample
#hole
HIT = True
NOHIT = False
def generate_card():
u"""Generate card
5x5 center(3 rows 3 columns)Card with a hole in
B(1st row) 1 - 15
I(2nd row) 16 - 30
N(3rd row) 31 - 45
G(4th row) 46 - 60
O(5th row) 61 - 75
:returns: array card, length=25
"""
cards = []
for i in range(5):
cards.extend(sample(range(15 * i + 1, 15 * (i + 1)), 5))
cards[12] = HIT
return cards
def check_bingo(card):
u"""Whether you are BINGO
Judgment only
param: array
:returns: boolean
"""
if card.count(HIT) < 5:
return False
for i in range(5):
if NOHIT not in card[i * 5: (i + 1) * 5]:
return True
for i in range(5):
if NOHIT not in card[i: i + 21: 5]:
return True
if NOHIT not in card[0: 24: 6]:
return True
if NOHIT not in card[4: 21: 4]:
return True
return False
def print_card(card):
for i, v in enumerate(card):
if v == HIT:
v = "o"
elif v == NOHIT:
v = "x"
sys.stdout.write("%3s" % str(v))
if (i % 5 == 4):
print()
print()
try:
times = int(sys.argv[1])
except IndexError:
times = 5
try:
card_num = int(sys.argv[2])
except IndexError:
card_num = 10000
hit_count = 0
for i in range(card_num):
card = generate_card()
lots = sample(range(1, 76), times)
card_hole = [(HIT if (x == HIT or x in lots) else NOHIT) for x in card]
# print_card(card)
# print_card(card_hole)
if check_bingo(card_hole):
hit_count += 1
print(str(times) + u"Probability of BINGO even one at the first time:")
p = hit_count / card_num
print("%s (%.1f %%)" % (str(p), p * 100))
Gist: https://gist.github.com/0c11f757334ba9ef7b1f
input: Number of times to turn the lottery machine Number of cards (number of simulations) output: Probability of even one BINGO
The explanation of each function should be mostly understood in the comments
The part where you can write like Python I think that the part that judges whether the card (BINGO card) is hit or not can be written like Python (I just wanted to make a process here)
#Judgment in the 4th column
NOHIT not in card[3:3 + 21:5]
#Judgment diagonally from top left to bottom right
NOHIT not in card[0:24:6]
Python arrays can be retrieved with array [start: end: step], so judgments can be written smartly.
Execution output example
>> python3 bingo.py 5 10000
Probability of even one BINGO in the 5th time:
0.0003 (0.0 %)
It doesn't matter, but what I learned in Flake 8 this time as a Python coding standard You have to open two lines between functions Do not put spaces on the ** right side ** of the array colon (same as the comma in the argument)
I still don't know how to write a doc block, so I'll study
Recommended Posts