.. title: Brute Force Works .. slug: brute-force-works .. date: 2015-10-28 15:24:41 UTC .. tags: python .. category: .. link: .. description: .. type: text Last night, Juanjo Conti tweeted this: .. raw:: html

Usando exactamente una vez los dígitos 1, 3, 4 y 6 y cualquiera de las cuatro operaciones básicas, obtener 24.

— Juanjo Conti (@jjconti) octubre 27, 2015
Or, in english: "Using exactly once the digits 1,3,4 and 6, and any of the four basic operations, obtain 24." I first spent a couple of minutes thinking about it and then it hit me: there is no point in **thinking** this sort of problem, because: 1) Brute forcing it will take less time 2) What you do while "thinking" it is sort of lame, isn't it? So, here is a more-or-less general solution for any of these problems. .. code:: python from __future__ import print_function, division import itertools numbers = ['1','3','4','6'] target = 24 # Having '' as an operation allows for solution (14-6)*3, which # may or may not be valid depending on rule interpretation. operations = ['*','/','+','-',''] t1='(({0}{4}{1}){5}{2}){6}{3}' t2='{0}{4}({1}{5}({2}{6}{3}))' for nums in itertools.permutations(numbers): for ops1 in itertools.combinations_with_replacement(operations, 3): for ops2 in itertools.permutations(ops1): for t in (t1, t2): s = t.format(*(nums+ops2)) #print(repr(s)) try: if eval(s) == target: print(s) except (ZeroDivisionError, SyntaxError, TypeError): continue Of course you can make it solve any problem of this class by adjusting numbers and target. There is also a possible extra solution if ``eval(s) == -target`` where you just need to add a unary - to the expression, but who cares. Did I miss something? Is this really a general solution?