Python实现1-9数组形成的结果为100的所有运算式
生活随笔
收集整理的這篇文章主要介紹了
Python实现1-9数组形成的结果为100的所有运算式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題:
編寫一個在1,2,…,9(順序不能變)數字之間插入+或-或什么都不插入,使得計算結果總是100的程序,并輸出所有的可能性。例如: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進制數,得到運算符數組arr = []for index in range(8):index = 7 - indexarr.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, formulaif __name__ == '__main__':#所有可能的結果total = 3 ** 8for i in range(total):res, formula = isHundred(i)if res == 100:print(formula+' = 100')?結果:
/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?
轉載于:https://www.cnblogs.com/wkcagd/p/7775102.html
總結
以上是生活随笔為你收集整理的Python实现1-9数组形成的结果为100的所有运算式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS-7.0.中安装与配置Tom
- 下一篇: jquery和bottstrap