Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Recursive two-tuple iterator solution in Clear category for Reverse Engineer by macfreek
from fractions import Fraction
from random import randint
import itertools
def uniqueSelections(items, n):
"""selections takes an unordered set of n elements (not necessarily distinct) from the sequence.
combination with replacement
Example: Selections of 2 letters from 'ABCD':
AA AB AC AD BB BC BD CC CD DD
combinations() is similar to itertools.combinations_with_replacement(), but is guaranteed to
work for infinite iterators.
For example, an iteration of 3-dimensional integers yields
(1,1,1) (1,1,2) (1,2,2) (2,2,2) (1,1,3) (1,2,3) (2,1,3) (2,2,3) (1,3,3) (2,3,3) ...
Compare this to itertools.combinations_with_replacement(), which would yield
(1,1,1) (1,1,2) (1,1,3) (1,1,4) (1,1,5) .... and never reach e.g. (1,2,2).
"""
if n==0:
yield []
else:
saved = []
for item in items:
saved.append(item)
for cc in uniqueSelections(saved, n-1):
yield cc+[item]
def expressions():
"""yield increasingly complex expressions with variables x and y, and binary operators +, -, * and /."""
yield "x"
yield "y"
yield "0" # x-x
yield "1" # x/x
for left, right in uniqueSelections(expressions(), 2):
if left == "0":
if right[0] not in ("0","-"):
yield "-"+right
elif right == "0":
pass
elif left == "1" and right == "1":
yield "("+left+"+"+right+")"
elif right == "1":
yield "("+left+"+"+right+")"
yield "("+left+"-"+right+")"
elif left == right:
yield "("+left+"+"+right+")"
yield "("+left+"*"+right+")"
else:
yield "("+left+"+"+right+")"
yield "("+left+"-"+right+")"
yield "("+right+"-"+left+")"
yield "("+left+"*"+right+")"
yield "("+left+"/"+right+")"
yield "("+right+"/"+left+")"
def checkio(steps):
def test_expression(expression, steps):
for x,y,solution in steps:
x = Fraction(x,1)
y = Fraction(y,1)
try:
result = eval(expression)
except ZeroDivisionError:
result = "ZeroDivisionError"
if [result.numerator, result.denominator] != solution:
return False
return True
for expression in expressions():
if test_expression(expression, steps):
return [expression, randint(-100, 100), randint(-100, 100)]
return ["1", 0, 99]
April 8, 2014