The Long Way to a Small, Angry Planet (Wayfarers, #1)
Review:Loved it. Reminded me a little of McMaster Bujold's Vorkosigan books, which is a very good thing. |
Review:Loved it. Reminded me a little of McMaster Bujold's Vorkosigan books, which is a very good thing. |
Review:The author's usual humour, applied to a sort of detective mistery? Nice solution to the puzzle, BTW. |
Review:Even crack cocaine gets boring after you have had enough. |
Review:Gack, I want the last one! I never noticed it was not out yet! Ok, pre-ordered :-P |
Last night, Juanjo Conti tweeted this:
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:
Brute forcing it will take less time
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.
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?