Skip to content

Instantly share code, notes, and snippets.

@hammeiam
Created November 27, 2018 22:17
Show Gist options
  • Save hammeiam/d85a8c721f8029b989cfb80accd8bb6e to your computer and use it in GitHub Desktop.
Save hammeiam/d85a8c721f8029b989cfb80accd8bb6e to your computer and use it in GitHub Desktop.
import itertools
"""
The following math problem illustrates the essence of hacking:
Use each of the numbers 1, 3, 4, and 6 exactly once with any of the four basic math operations (addition, subtraction, multiplication, and division) to total 24. Each number must be used once and only once, and you may define the order of operations; for example, 3 * (4 + 6) + 1 = 31 is valid, however incorrect, since it doesn’t total 24.
The rules for this problem are well defined and simple, yet the answer eludes many. Like the solution to this problem (shown on the last page of this book), hacked solutions follow the rules of the system, but they use those rules in counterintuitive ways.
"""
nums = ['1','3','4','6']
ops = ['+','-','/','*']
op_combinations = itertools.product(ops, repeat=3)
answers = []
def generate_parens(ops, nums):
yield f"{nums[0]} {ops[0]} {nums[1]} {ops[1]} {nums[2]} {ops[2]} {nums[3]}"
yield f"({nums[0]} {ops[0]} {nums[1]}) {ops[1]} ({nums[2]} {ops[2]} {nums[3]})"
yield f"{nums[0]} {ops[0]} ({nums[1]} {ops[1]} {nums[2]}) {ops[2]} {nums[3]}"
yield f"({nums[0]} {ops[0]} {nums[1]} {ops[1]} {nums[2]}) {ops[2]} {nums[3]}"
yield f"{nums[0]} {ops[0]} ({nums[1]} {ops[1]} {nums[2]} {ops[2]} {nums[3]})"
yield f"(({nums[0]} {ops[0]} {nums[1]}) {ops[1]} {nums[2]}) {ops[2]} {nums[3]}"
yield f"({nums[0]} {ops[0]} ({nums[1]} {ops[1]} {nums[2]})) {ops[2]} {nums[3]}"
yield f"{nums[0]} {ops[0]} (({nums[1]} {ops[1]} {nums[2]}) {ops[2]} {nums[3]})"
yield f"{nums[0]} {ops[0]} ({nums[1]} {ops[1]} ({nums[2]} {ops[2]} {nums[3]}))"
count = 0
for ops in op_combinations:
num_permutations = itertools.permutations(nums, 4)
for nums in num_permutations:
for exp in generate_parens(ops, nums):
try:
result = eval(exp)
except ZeroDivisionError:
pass
if result == 24:
answers.append(exp)
count += 1
print('Answers:')
print(answers)
print(count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment