Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Reverse Engineer by coells
from fractions import Fraction
from itertools import product
def expression(n = 0):
if not n: return ['x', 'y']
subexp = expression(n - 1)
subexp.extend('({}){}({})'.format(x, o, y) for x, y in product(subexp, repeat = 2) for o in '+-*/')
return subexp
def expr_eval(e, x, y):
try:
return Fraction(eval(e.replace('x', str(x)).replace('y', str(y))))
except (ZeroDivisionError):
return 'ZeroDivisionError'
def checkio(data):
expressions = expression(2)
for x, y, w in data:
r = w if w == 'ZeroDivisionError' else Fraction(w[0] / w[1])
expressions = [e for e in expressions if expr_eval(e, x, y) == r]
return [expressions[0], len(data), 11]
#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"
April 1, 2014
Comments: