Mainly Tech projects on Python and Electronic Design Automation.

Thursday, March 04, 2010

NPR 2002 Puzzle

A puzzle I copied from here via reddit:
1 2 3 4 5 6 7 8 9 = 2002
Put any combination of plus, times, and spaces between the digits on the left to make the identify true.
The answer was easy and was quick to compute.

I realised that you could evaluate all expressions where the numbers 1 through nine are separated by the permutations of either a null string, '', '+' or '*'

The answer came from the following:

>>> from itertools import product
>>> eqn = '%s'.join(list('123456789')) + '==2002'
>>> eqn
'1%s2%s3%s4%s5%s6%s7%s8%s9==2002'
>>> for ops in product(*[['', '+', '*']]*8):
if eval(eqn % ops):
print(eqn % ops)


1*23+45*6*7+89==2002
1*2+34*56+7+89==2002
>>>

So, there are two solutions.

1 comment:

  1. It also golfs:

    >>> from itertools import product as p;e='%s'.join(list('123456789'))+'==2002';print([e%q for q in p(*[['', '+', '*']]*8) if eval(e%q)])
    ['1*23+45*6*7+89==2002', '1*2+34*56+7+89==2002']
    >>>

    ReplyDelete

Followers

Subscribe Now: google

Add to Google Reader or Homepage

Go deh too!

whos.amung.us

Blog Archive