'''
February 2018 Math Puzzler
dvogel003@monroecc.edu 2/2/18
Between each pair of adjacent digits in the numbers given below, you are to
insert one of the operations +, -, ×, and/or ÷ to create an expression that
results in 100. You may include any number of parentheses to control the
order of operations, but changing the order of the digits and concatenating
the digits to form a number with two or more digits is not permitted. Note:
the operator " - " indicates subtraction, not negation.
For example, starting with the number 9861184, we can obtain a result of
100 as follows:
9 x 8 + 6 ÷ (1 + 1) x 8 + 4 = 100
Obtain a value of 100 by starting with each of the following seven-digit
numbers:
1) 3141592 2) 2718281 3) 1234567
Approach: Brute force all possible combinations of arithmetic operations
with all possible parentheses (just 1 set of parentheses).
'''
from __future__ import print_function #so this will work with Py 2.7
ops = ['+', '-', '*', '/']
argsList = [['3', '1', '4', '1', '5', '9', '2'], \
['2', '7', '1', '8', '2', '8', '1'], \
['1', '2', '3', '4', '5', '6', '7']]
for args in argsList: #For all 3 sets of numbers
print()
print("Solutions for: " + args[0] + args[1] + args[2] + \
args[3] + args[4] + args[5] + args[6])
#Check all possible left parenthesis locations
for left in range(5):
lpar = ['', '', '', '', '', ''] #Left parenthesis
lpar[left] = '('
#Check all right paren possibilities
for right in range(left, 5):
rpar = ['', '', '', '', '', ''] #Right parenthesis
rpar[right] = ')'
#Now test all the possible positions for the operators
for op5 in ops:
for op4 in ops:
for op3 in ops:
for op2 in ops:
for op1 in ops:
for op0 in ops:
fn = lpar[0] + args[0] + op0 + \
lpar[1] + args[1] + rpar[0] + op1 + \
lpar[2] + args[2] + rpar[1] + op2 + \
lpar[3] + args[3] + rpar[2] + op3 + \
lpar[4] + args[4] + rpar[3] + op4 + \
lpar[5] + args[5] + rpar[4] + op5 + \
args[6] + rpar[5]
#Ignore any divide by zero errors
try:
ans = eval(fn)
except ZeroDivisionError:
pass
#print(fn)
if ans == 100:
print(str(ans) + ' = ' + fn)