Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
No regex, no eval, use operators solution in Creative category for Safe Code by Merzix
from operator import add, sub, mul
import string
def safe_code(equation):
used_numbers = set(filter(str.isdigit, equation))
possible_numbers = set(string.digits) - used_numbers
reduction = {'-': sub,
'+': add,
'*': mul,
}
first, op, second = [None] * 3
left_part, result = equation.split('=')
for i in ('+', '*', '-'): # '-' should be last
op_index = left_part[1:].find(i)
if op_index >= 0:
op_index = left_part.find(i, 1)
first, second = left_part[:op_index], left_part[op_index+1:]
op = reduction[i]
break
for n in (first, second, result):
if (n[0] == '#' and len(n) > 1) or n[:2] == '-#':
possible_numbers.discard('0')
break
let = lambda pattern, digit: int(pattern.replace('#', digit))
for i in sorted(possible_numbers):
if op(let(first, i), let(second, i)) == let(result, i):
return int(i)
return -1
if __name__ == '__main__':
assert safe_code("#*11=##") == 2
assert safe_code("-5#*-1=5#") == 0
assert safe_code("##*##=302#") == 5
assert safe_code("19--45=5#") == -1
assert safe_code("#*13=#6") == 2 # added
assert safe_code("#*-13=-#6") == 2 # added
assert safe_code("-2+-8=-1#") == 0 # added
assert safe_code("#3#*4#=34639") == 7 # added
assert safe_code("-9-#=-11") == 2 # added
assert safe_code("-5-1#=-19") == 4 # added
assert safe_code("-9-#2=-11") == -1 # added
Sept. 17, 2018