Last active
May 16, 2017 19:18
-
-
Save mikepqr/315f811f5dffe88a902d9e84a81158b1 to your computer and use it in GitHub Desktop.
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 random | |
from collections import defaultdict | |
class circle(list): | |
'''Circular list, i.e. | |
>>> c = circle([1,2,3]) | |
>>> c[0], c[3], c[7] | |
(1, 1, 2) | |
''' | |
def __getitem__(self, i): | |
return list.__getitem__(self, i % len(self)) | |
def invert_mapping(dct): | |
inv = defaultdict(list) | |
for k, v in dct.items(): | |
inv[v].append(k) | |
return dict(inv) | |
def choose_targets(items): | |
items = circle(items) | |
targets = {source: random.choice((items[i-1], items[i+1])) | |
for i, source in enumerate(items)} | |
return targets | |
def count_unpecked(peckers): | |
chicks = peckers.keys() | |
peckees = invert_mapping(peckers).keys() | |
return len(chicks - peckees) | |
def simulate_chicks(nchicks=100): | |
chicks = range(nchicks) | |
peckers = choose_targets(chicks) | |
return count_unpecked(peckers) | |
def simulate_fn(fn, nsims=1000, *args, **kwargs): | |
return sum(fn(*args, **kwargs) for i in range(nsims))/nsims |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment