Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Brute force solution in Clear category for Reverse Engineer by nickie
from fractions import Fraction
from random import randrange
# Generate (and store in G) all possible expressions with exactly n operators
G = {0: ["x", "y"]}
def gen(n):
if n not in G:
G[n] = ["(" + e1 + op + e2 + ")" for i in range(n) for op in "+-*/"
for e1 in gen(i) for e2 in gen(n-i-1)]
return G[n]
# Evaluate an expression
def evaluate(e, x, y):
try:
return eval(e)
except ZeroDivisionError:
return "ZeroDivisionError"
# Generate a function that checks if expression e satisfies step s
def good(s):
x, y = Fraction(s[0]), Fraction(s[1])
r = s[2] if s[2] == "ZeroDivisionError" else Fraction(*s[2])
return lambda e: evaluate(e, x, y) == r
# Brute force, find the first expression to match
# Remember where you stopped the previous time
# Return a next point that is random but certainly not seen before
n, current, total = 0, 0, len(gen(0))
def checkio(steps):
global n, current, total
while True:
if current >= total:
n, current, total = n+1, 0, len(gen(n+1))
e = gen(n)[current]
if not all(good(s)(e) for s in steps):
current += 1
continue
if steps == []:
x = y = 0
else:
x = max(s[0] for s in steps) + randrange(1, 5)
y = min(s[1] for s in steps) - randrange(1, 5)
return [e, x, y]
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print(checkio([]))
print(checkio([[5, 7, [12, 1]]]))
print(checkio([[5, 7, [12, 1]], [1, 2, [3, 1]]]))
Jan. 30, 2014
Comments: