Problem:
Write a program that inserts + or-or nothing between 1,2,...,9 (the order cannot be changed), so that the result of the calculation is always 100 and outputs all the possibilities. For example: 1 + 2 + 34–5 + 67–8 + 9 = 100.
From functools Import reduceoperator = { 1: ' + ', 2: '-', 0: '}base = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']def ishundred (num): #转化为8位3进制数, get an array of operators arr = [] for Index in range (8): index = 7-index Arr.app End (num//(3 * index)) num-= (num/(3 * * index)) * (3 * * index) arr = map (lambda x:operator[x], arr) #合 And get the op- formula = reduce (lambda x, y:x + y, zip (base, arr)) formula = List (Formula) formula.append (' 9 ')
formula = ". Join (Formula) #计算运算式结果 res = eval (Formula) return res, formulaif __name__ = = ' __main__ ': #所有可能的结果 Total = 3 * * 8 for I in range: res, formula = ishundred (i) if res = =: p Rint (formula+ ' = 100 ')
Results:
/usr/bin/python3.5/home/kang/workspace/qt3d/test.py123+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
Python implements 1-9 arrays to form all expressions with a result of 100