编程语言


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

网络编程 Python实现1-9数组形成的结果为100的所有运算式的示例 06-21

问题:

编写一个在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的所有运算式的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持积木网。

django实现同一个ip十分钟内只能注册一次的实例
很多小伙伴都会有这样的问题,说一个ip地址十分钟内之内注册一次,用来防止用户来重复注册带来不必要的麻烦逻辑:取ip,在数据库找ip是否存在,

基于Python os模块常用命令介绍
1、os.name---判断现在正在实用的平台,Windows返回'nt';linux返回'posix'2、os.getcwd()---得到当前工作的目录。3、os.listdir()---4、os.remove---删除指定文件5、os.rmdi

python嵌套字典比较值与取值的实现示例
前言本文通过示例给大家介绍了python嵌套字典比较值,取值,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。示例代码#取值impo


编辑:编程语言

标签:示例,给大家,嵌套,数组,字典