Sheesh, I wish I knew enough about coding to really make sense of the many examples in “Easy AI with Python”.

Graffiti in Berlin, near Görlitzer Bahnhof

I’m happy about the little I know concerning Bash-scripting and Perl, without this my cut-up-twitter-experiment couldn’t even have been dreamt of. But back to AI + Python. I was surprised to learn that all it takes to recreate a Mastermind-like-game is 30 lines of code:


import random
from itertools import izip, imap
digits = 4
fmt = ‘%0’ + str(digits) + ’d’
searchspace = tuple([tuple(map(int,fmt % i)) for i in
   range(0,10**digits)])
def compare(a, b, map=imap, sum=sum, zip=izip, min=min):
    count1 = [0] * 10
    count2 = [0] * 10
    strikes = 0
    for dig1, dig2 in zip(a,b):
        if dig1 == dig2:
            strikes += 1
        count1[dig1] += 1
        count2[dig2] += 1
    balls = sum(map(min, count1, count2)) - strikes
    return (strikes, balls)

def rungame(target, strategy, maxtries=15): possibles = list(searchspace) for i in xrange(maxtries): g = strategy(i, possibles) print “Out of %7d possibilities. I’ll guess %r” % (len(possibles), g), score = compare(g, target) print ‘ —> ‘, score if score[0] == digits: print “That’s it. After %d tries, I won.” % (i+1,) break possibles = [n for n in possibles if compare(g, n) == score] return i+1

def s_allrand(i, possibles): ‘Simple strategy that randomly chooses one remaining possibility’ return random.choice(possibles) hiddencode = (4, 3, 3, 7) rungame(hiddencode, s_allrand)

Take a look at the slides to learn about simple neural nets, a solution-finder to the Eight queens puzzle, or ways to create Sudoku- and Sliding-Block-style-games. Apparently it’s easy to understand and great for teaching Python. I’ll give it a try this weekend, I predict lots of FAIL and burning eyes from staring at spaghetti-code. (The picture above was taken in Berlin, near Görlitzer Bahnhof)