Skip to content

Instantly share code, notes, and snippets.

@fferri
Created April 10, 2018 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fferri/9336d64e113bf188a70e6ceea69ebf8d to your computer and use it in GitHub Desktop.
Save fferri/9336d64e113bf188a70e6ceea69ebf8d to your computer and use it in GitHub Desktop.
# solution to puzzle https://www.youtube.com/watch?v=LyyHt7NfBxI
# "can you make 24 from 3 3 8 8 using only + - * / ( ) ?"
class Add:
def __init__(self, a, b):
self.a, self.b = a, b
def eval(self):
return self.a.eval() + self.b.eval()
def __repr__(self):
return '({!r} + {!r})'.format(self.a, self.b)
class Sub:
def __init__(self, a, b):
self.a, self.b = a, b
def eval(self):
return self.a.eval() - self.b.eval()
def __repr__(self):
return '({!r} - {!r})'.format(self.a, self.b)
class Mul:
def __init__(self, a, b):
self.a, self.b = a, b
def eval(self):
return self.a.eval() * self.b.eval()
def __repr__(self):
return '({!r} * {!r})'.format(self.a, self.b)
class Div:
def __init__(self, a, b):
self.a, self.b = a, b
def eval(self):
return self.a.eval() / self.b.eval()
def __repr__(self):
return '({!r} / {!r})'.format(self.a, self.b)
class Const:
def __init__(self, k):
self.k = k
def eval(self):
return self.k
def __repr__(self):
return str(self.k)
def split(s, a=[], b=[], minsize=0):
if s:
yield from split(s[1:], a + [s[0]], b, minsize)
yield from split(s[1:], a, b + [s[0]], minsize)
else:
if len(a) >= minsize and len(b) >= minsize:
yield a, b
def f(s):
if len(s) == 1:
yield Const(s[0])
else:
for a, b in split(s,minsize=1):
for op in (Add, Sub, Mul, Div):
for xa in f(a):
for xb in f(b):
yield op(xa, xb)
for x in f([3,3,8,8]):
try:
r = x.eval()
if abs(r - 24) > 0.01: continue
except ZeroDivisionError:
continue
print('{} = {}'.format(x, r))
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment