Skip to content

Instantly share code, notes, and snippets.

@dcoles
Last active December 20, 2021 21:53
Show Gist options
  • Save dcoles/3a0095e49a8c0e6daf4fa2bf84f4182d to your computer and use it in GitHub Desktop.
Save dcoles/3a0095e49a8c0e6daf4fa2bf84f4182d to your computer and use it in GitHub Desktop.
By only adding + - * into the string 452874 (in that order), how many way can you get to -18?
"""
By only adding + - * into the string 452874 (in that order),
how many way can you get to -18?
"""
N = "452874"
M = -18
OPERATIONS = [None, '+', '-', '*']
for n in range(4**(len(N) - 1)):
start = 0
end = 1
equation = []
for op in [OPERATIONS[n // 4 ** x % 4] for x in range(len(N) - 1)]:
if not op:
end += 1
else:
equation.append(N[start:end])
equation.append(op)
start = end
end = start + 1
equation.append(N[start:])
e = ' '.join(equation)
result = eval(e)
if result == M:
print(f'{e} = {result}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment