Skip to content

Instantly share code, notes, and snippets.

@jiaaro jiaaro/organism.py
Last active Jan 4, 2016

Embed
What would you like to do?
NOTE: organism.py belongs in a directory "breeder"
#!/usr/bin/env python
import ast
from os.path import isfile
from hashlib import md5
from random import randint, choice
from glob import glob
import re
# scratch area
"""
"abcdefghijklmnopqrstuvwxyz1234567890+=-_~`{}[]\|';:,\\!@#$%^&*()"
"abcdefghijklmnopqrstuvwxyz1234567890+=-_~`{}[]\|';:,\\!@#$%^&*()"
"abcdefghijklmnopqrstuvwxyz1234567890+=-_~`{}[]\|';:,\\!@#$%^&*()"
False True None
"""
# random index
r = lambda codes: randint(0, len(codes) - 1)
get_code = lambda f: open(f, 'r').read()
choose_mate = lambda: choice(glob("./*.py"))
def swap(codes, a, b):
codes[a], codes[b] = codes[b], codes[a]
splits = (
(lambda code: (list(code), '',)),
(lambda code: (code.split(' '), ' ',)),
(lambda code: (code.split('\n'), '\n',)),
(lambda code: (code.split(' '), ' ',)),
(lambda code: (code.split('\n '), '\n ',)),
)
mutators = (
(lambda codes: codes.insert(r(codes), choice(codes))),
(lambda codes: codes.insert(r(codes), choice(codes))),
(lambda codes: swap(codes, r(codes), r(codes))),
(lambda codes: swap(codes, r(codes), r(codes))),
(lambda codes: codes.pop(r(codes))),
)
def mutate(code_str):
splitter = choice(splits)
mutator = choice(mutators)
codes, joiner = splitter(code_str)
mutator(codes)
return joiner.join(codes) or code_str
def combine_code(code1, code2):
code1 = code1.split("\n")
code2 = code2.split("\n")
out_len = max([len(code1), len(code2)])
out = []
for i in range(out_len):
code = [code1, code2][i % 2]
out += code[i:i+1]
return '\n'.join(out)
for _ in range(50):
# breed
child_code = get_code(__file__)
child_code = combine_code(child_code, get_code(choose_mate()))
child_code = mutate(child_code)
child_code = mutate(child_code)
child_code = mutate(child_code)
try: ast.parse(child_code)
except SyntaxError: continue
child_name = "./{}.py".format(md5(child_code).hexdigest())
if not isfile(child_name):
with open(child_name, 'w') as f:
f.write(child_code)
#!/usr/bin/env python
from glob import glob
import os
from os.path import getsize
import random
def get_free_space_mb():
st = os.statvfs('/')
return st.f_bavail * st.f_frsize / 1024 / 1024.0
orgs = glob("./*.py")
random.shuffle(orgs)
big_files = iter(sorted(orgs, key=getsize, reverse=True))
all_files = iter(orgs)
killed = 0
while get_free_space_mb() < (5 * 1024):
try:
os.unlink(big_files.next())
killed += 1
os.unlink(all_files.next())
killed += 1
except OSError:
pass
if killed:
print "killed {0} big organisms".format(killed)
#!/bin/bash
cd ./breeder
while true; do
f=$(python -c "import glob, random; print(random.choice(glob.glob('./*.py')))");
python "$f" 2> /dev/null;
if [[ $? != 0 ]]; then
rm "$f";
echo -n '.'
else
echo
echo "$f"
fi
python ../predator.py
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.