Python Implementation 1-9 array form result 100 for all computational formula examples, python1-9
Problem:
Write one in 1, 2 ,..., 9 (the sequence cannot be changed) insert + or-between numbers or do nothing, so that the calculation result is always 100 of the program and all possibilities are output. For example, 1 + 2 + 34-5 + 67-8 + 9 = 100.
From functools import reduce operator = {1: '+', 2: '-', 0: ''} base = ['1', '2', '3 ', '4', '5', '6', '7', '8', '9'] def isHundred (num): # convert it to an 8-digit three-digit number, obtain the array arr = [] for index in range (8): index = 7-index arr. append (num // (3 ** index) num-= (num // (3 ** index) * (3 ** index) arr = map (lambda x: operator [x], arr) # merge to obtain the formula = reduce (lambda x, y: x + y, zip (base, arr) formula = list (formula) formula. append ('9') formula = ''. join (formula) # Calculation formula result res = eval (formula) return res, formula if _ name _ = '_ main __': # All possible RESULTS total = 3 ** 8 for I in range (total): res, formula = isHundred (I) if res = 100: print (formula + '= 100 ')
Result:
/usr/bin/python3.5 /home/kang/workspace/Qt3d/test.py 123+45-67+8-9 = 100123+4-5+67-89 = 100123-45-67+89 = 100123-4-5-6-7+8-9 = 10012+3+4+5-6-7+89 = 10012+3-4+5+67+8+9 = 10012-3-4+5-6+7+89 = 1001+23-4+56+7+8+9 = 1001+23-4+5+6+78-9 = 1001+2+34-5+67-8+9 = 1001+2+3-4+5+6+78+9 = 100
In the above example of all the operators whose Python implementation result is 100 in array 1-9, I hope to give you a reference, we also hope that you can support the customer's home.