Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Reverse Engineer by Tsutomu-KKE
from fractions import Fraction
def checkio(steps):
if steps == []: return ['x+y', 1, 2]
els = ['x', 'y']
exs = set()
for i in range(2):
tmp = []
for x in els:
for y in els:
if x <= y: tmp.append('(%s+%s)' % (x, y))
if x != y: tmp.append('(%s-%s)' % (x, y))
if x <= y: tmp.append('(%s*%s)' % (x, y))
if x != y: tmp.append('(%s/%s)' % (x, y))
els = tmp + ['x', 'y']
for el in els: exs.add(el)
for ex in exs:
err = False
for x, y, s in steps:
if err: break
x, y = Fraction(x), Fraction(y)
try:
r = eval(ex)
r = [r.numerator, r.denominator]
except:
r = 'ZeroDivisionError'
err = r != s
if not err: return [ex, len(steps) * 7 + 1, len(steps) * 13 + 2]
return ['x', 0, 0]
#This part is using only for self-testing
#It's "light" version of the grader
#The hidden expression should be correct (non x/(y-y))
if __name__ == '__main__':
def test_it(hidden_expression, solver):
from fractions import Fraction
from random import randint
def check_is_right(guess, expression):
for _ in range(10):
result_guess = 0
result_expr = 1
for __ in range(100):
x, y = Fraction(randint(-100, 100)), Fraction(randint(-100, 100))
try:
result_expr = eval(expression)
result_guess = eval(guess)
except ZeroDivisionError:
continue
break
if result_guess != result_expr:
return False
return True
input_data = []
for step in range(50):
user_guess, x_real, y_real = solver(input_data)
x = Fraction(x_real)
y = Fraction(y_real)
try:
result = eval(hidden_expression)
output = [result.numerator, result.denominator]
except ZeroDivisionError:
output = "ZeroDivisionError"
input_data.append([x_real, y_real, output])
if check_is_right(user_guess, hidden_expression):
return True
else:
return False
assert test_it("x+y", checkio), "x+y"
assert test_it("x*y", checkio), "x*y"
assert test_it("x-y", checkio), "x-y"
assert test_it("x/y", checkio), "x/y"
March 4, 2014
Comments: