October 12, 2008, at 08:12 PM

20081012

After reading the brilliant Introduction to Dynamic Programming I have decided to commit another Master Mind related post :P I am interested in the not so technical yet interesting subject of programming styles ...

My last take on the subjects aims at reducing the cognitive load of the functional version of the play method by creating meaningfully named functions and using what some would call magic (argument unpacking using *) to get rid of the ugly if ... return statement :P

def play(self, guess):
    """ play return a tuple (correct, misplaced) """

    def black(secret, guess):
        return len([(s,g) for (s,g) in zip(secret, guess) if s==g])

    def white(secret, guess):
        distinct = [(s,g) for (s,g) in zip(secret, guess) if s!=g]
        return  misplaced(*map(list, zip(*distinct)))

    def misplaced(secret=[], guess=[]):
        return sum(min(secret.count(g), guess.count(g))
                   for g in set(guess))

    return  black(self.secret, guess), white(self.secret, guess)

Which Raphael likes !!!

Beware though, misplaced is a convenience function that is not pythonically defined because all call to misplaced with a missing argument will share the same list! Why? Because in Python def is an executable statement ...

def foo(arg=[]):
    print a
    a.append('a')
    print a

>>> foo()
[]
['a']
>>> foo()
['a']
['a', 'a']

Despite the cheesy promotional segments The Time Paradox is a pretty interesting watch.

blog comments powered by Disqus