Skip to content

Instantly share code, notes, and snippets.

@robert-malai
Created October 7, 2019 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robert-malai/c07f7f432d87c867578ae2592e8c37c0 to your computer and use it in GitHub Desktop.
Save robert-malai/c07f7f432d87c867578ae2592e8c37c0 to your computer and use it in GitHub Desktop.
Digits and Operators problem
from collections import OrderedDict
DIGITS: str = '123456789'
TARGET: int = 101
OPCODE = OrderedDict([
('0', ''),
('1', '*'),
('2', '-'),
('3', '+'),
])
COUNT: int = len(DIGITS)
BASE: int = len(OPCODE.keys())
LIMIT: str = list(OPCODE.keys())[-1] * (COUNT - 1)
def number_to_base(n: int, b: int) -> str:
if n == 0:
return '0'
digits = []
while n:
digits.append(int(n % b))
n //= b
return ''.join(str(d) for d in digits[::-1])
def interlace_ops_to_digits(ops: str, digits: str) -> str:
assert len(ops) == len(digits) - 1
operations = [OPCODE[op] for op in ops] + ['']
expression = [val for pair in zip(digits, operations) for val in pair]
return ''.join(expression)
x: int = 0
solutions = []
while True:
ops = number_to_base(x, BASE).rjust(COUNT - 1, '0')
expr = interlace_ops_to_digits(ops, DIGITS)
result = eval(expr)
message = f"Operations {ops}: {expr} = {result}"
if result == TARGET:
solutions.append(message)
message += " EVRIKA !!!"
print(message)
if ops == LIMIT:
print("All combinations were executed")
break
else:
x = x + 1
if len(solutions) > 0:
print("The following solutions were identified")
for sol in solutions:
print(sol)
else:
print("No solution found !")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment