問題:
編寫一個在1,2,…,9(順序不能變)數字之間插入+或-或什么都不插入,使得計算結果總是100的程序,并輸出所有的可能性。例如:1 + 2 + 34–5 + 67–8 + 9 = 100。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
from functools import reduce operator = { 1: '+', 2: '-', 0: '' } base = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] def isHundred(num): #轉化為8位3進制數,得到運算符數組 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) #合并得到運算式 formula = reduce(lambda x, y: x + y, zip(base, arr)) formula = list(formula) formula.append('9') formula = ''.join(formula) #計算運算式結果 res = eval(formula) return res, formula if __name__ == '__main__': #所有可能的結果 total = 3 ** 8 for i in range(total): res, formula = isHundred(i) if res == 100: print(formula+' = 100') |
結果:
1
2
3
4
5
6
7
8
9
10
11
12
|
/usr/bin/python3.5 /home/kang/workspace/Qt3d/test.py 123+45-67+8-9 = 100 123+4-5+67-89 = 100 123-45-67+89 = 100 123-4-5-6-7+8-9 = 100 12+3+4+5-6-7+89 = 100 12+3-4+5+67+8+9 = 100 12-3-4+5-6+7+89 = 100 1+23-4+56+7+8+9 = 100 1+23-4+5+6+78-9 = 100 1+2+34-5+67-8+9 = 100 1+2+3-4+5+6+78+9 = 100 |
以上這篇Python實現1-9數組形成的結果為100的所有運算式的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/wkcagd/archive/2017/11/02/7775102.html