Created
December 16, 2020 16:32
-
-
Save Infernio/1f08853cf59b65341af3cfdcbbde6f4d to your computer and use it in GitHub Desktop.
Decently fast 'dice simulator' in Python for calculating chances and expected value for n throws
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import time | |
from collections import Counter | |
from random import randint | |
def chances(results): | |
total = sum(results.values()) | |
return {k: v / total for k, v in results.items()} | |
def avg(chances): | |
ret = 0.0 | |
for val, chance in chances.items(): | |
ret += val * chance | |
return ret | |
def make_readable(chances): | |
return {k: '{}%'.format(v * 100) for k, v in chances.items()} | |
def perform_throws(n): | |
results = Counter() | |
for i in range(n): | |
results[randint(1, 6)] += 1 | |
cha = chances(results) | |
print('End Result:\n Chances: %s\n Average: %f' % ( | |
make_readable(cha), avg(cha))) | |
def main(): | |
if len(sys.argv) < 2: | |
print('Usage: dice.py <number of throws>') | |
sys.exit(1) | |
perform_throws(int(sys.argv[1])) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment