Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Try 'em all solution in Uncategorized category for Reverse Engineer by htamas
from fractions import Fraction
from itertools import count
# enumerate pairs of nonnegative integers
def pair(n):
a = int(n**(1/2))
b = n - a*a
return min(a, b), min(a, 2*a-b)
# enumerate bivariate arithmetic expressions
def expr(n):
if n == 0:
return 'x'
elif n == 1:
return 'y'
else:
subexpr, op = divmod(n-2, 4)
a, b = pair(subexpr)
return '(' + expr(a) + ')' + '+-*/'[op] + '(' + expr(b) + ')'
# check an expression at a given location
def test(e, x, y, z):
try:
x, y, z = Fraction(x), Fraction(y), z if type(z) is str else Fraction(*z)
return eval(e.replace('x', repr(x)).replace('y', repr(y))) == z
except ZeroDivisionError as err:
return type(err).__name__ == z
# try all expressions until we succeed
def checkio(steps):
for i in count():
e = expr(i)
if all(test(e, x, y, z) for x, y, z in steps):
return [e] + list(pair(len(steps)))
Jan. 29, 2014
Comments: