Just for fun: Countdown numbers game solver

Paul Rubin http
Sun Jan 20 16:35:58 EST 2008


dg.google.groups at thesamovar.net writes:
> Unfortunately I realise I stated the problem imprecisely. You're only
> allowed to use each number once (otherwise there's a trivial solution
> for every problem, i.e. x/x + x/x + x/x + ... + x/x repeated y times
> for target y given any source number x). Trying your program on 234
> from [100,9,7,6,3,1] gives you 9*9*3-9 using the 9 three times.

Here is a pretty inefficient solution.  It doesn't find 234 but it
does find 253 twice:

    from operator import *

    def countdown(nums, ops, trace):
        n0 = nums[0]
        if len(nums) == 1:
            yield n0, str(n0)
            return
        for i,n in enumerate(nums[1:]):
            for f in ops:
                for r,t in countdown(nums[1:i] + nums[i+1:], [add, mul, sub], trace):
                    if f != div or r != 0 and n0 % r == 0:
                        yield f(n0, r), '%s(%s,%s)'% (f.__name__, n0, t)

    def search(nums, target):
        for x,t in countdown(nums, [add, mul, sub, div], []):
            if x == target:
                print x,t

    search([100,9,7,6,3,1], 253)



More information about the Python-list mailing list