Python算法输出1-9数组形成的结果为100的所有运算式
2019/7/13 22:42:00
本文主要是介绍Python算法输出1-9数组形成的结果为100的所有运算式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
问题:
编写一个在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算法输出1-9数组形成的结果为100的所有运算式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python