Python算法输出1-9数组形成的结果为100的所有运算式

yipeiwu_com7年前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

下面再看一个小实例:

题目:输入三个整数x,y,z,请把这三个数由小到大输出。

程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。

程序源代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
l = []
for i in range(3):
 x = int(raw_input('integer:\n'))
 l.append(x)
l.sort()
print l

以上实例输出结果为:

integer:
8
integer:
5
integer:
6
[5, 6, 8]

总结

以上就是小编分享给大家的有关Python的实例,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:Python定时器实例代码Python生成数字图片代码分享Python中enumerate函数代码解析等,有什么问题可以随时留言,小编会及时回复大家的。

相关文章

利用python批量检查网站的可用性

前言 随着站点的增多,管理复杂性也上来了,俗话说:人多了不好带,我发现站点多了也不好管,因为这些站点里有重要的也有不重要的,重要核心的站点当然就管理的多一些,像一些万年都不出一次问题的,...

Python实现按逗号分隔列表的方法

方法一: def commaSpiltList(self, listData): listData = list(listData) strs = str(listData[0]...

教你安装python Django(图文)

教你安装python Django(图文)

安装环境:python版本2.7.5 ,win7系统安装Djangohttps://www.djangoproject.com/download/ 官方下载Django-1.5.5.ta...

python实现杨辉三角思路

程序输出需要实现如下效果: [1] [1,1] [1,2,1] [1,3,3,1] ...... 方法:迭代,生成器 def triangles() L = [1] while...

Python中的测试模块unittest和doctest的使用教程

我要坦白一点。尽管我是一个应用相当广泛的公共域 Python 库的创造者,但在我的模块中引入的单元测试是非常不系统的。实际上,那些测试大部分 是包括在 gnosis.xml.pickle...