Python实现1-9数组形成的结果为100的所有运算式的示例

yipeiwu_com6年前Python基础

问题:

编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如: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): 
 
 #转化为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')

 结果:

/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的所有运算式的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pip install urllib2不能安装的解决方法

python35 urllib2 不能用 Could not find a version that satisfies the requirement urllib2 (from...

Python发送http请求解析返回json的实例

python发起http请求,并解析返回的json字符串的小demo,方便以后用到。 #! /usr/bin/env python # -*- coding:gbk -*-...

Python使用re模块正则提取字符串中括号内的内容示例

本文实例讲述了Python使用re模块正则提取字符串中括号内的内容操作。分享给大家供大家参考,具体如下: 直接上代码吧: # -*- coding:utf-8 -*- #! pyth...

python自动化报告的输出用例详解

python自动化报告的输出用例详解

1、设计简单的用例 2、设计用例    以TestBaiduLinks.py命名 # coding:utf-8 from selenium import webdriver imp...

Python流程控制 if else实现解析

Python流程控制 if else实现解析

一、流程控制 假如把程序比做走路,那我们到现在为止,一直走的都是直路,还没遇到过分岔口。当遇到分岔口时,你得判断哪条岔路是你要走的路,如果我们想让程序也能处理这样的判断,该怎么办?很简...