By only adding + - * into the string 452874 (in that order), how many way can you get to -18?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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