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

以上这篇Python实现1-9数组形成的结果为100的所有运算式的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详谈python在windows中的文件路径问题

在使用python通过open()函数来打开文件的时候,传递绝对路径给open()的时候,发现路径参数的内容与想象中的有所出入: 由于windows的路径分隔符使用的是反斜杠\,它刚刚好...

python实现旋转和水平翻转的方法

如下所示: # coding=utf-8 import glob import os from PIL import Image def rotate_270(imgae):...

从列表或字典创建Pandas的DataFrame对象的方法

从列表或字典创建Pandas的DataFrame对象的方法

介绍 每当我使用pandas进行分析时,我的第一个目标是使用众多可用选项中的一个将数据导入Pandas的DataFrame 。 对于绝大多数情况下,我使用的 read_excel ,...

Python实现对字典分别按键(key)和值(value)进行排序的方法分析

本文实例讲述了Python实现对字典分别按键(key)和值(value)进行排序的方法。分享给大家供大家参考,具体如下: 方法一: #使用sorted函数进行排序 ''' sorte...

Django中的文件的上传的几种方式

PS:这段时间有点不在状态,刚刚找回那个状态,那么我们继续曾经的梦想 今天我们来补充一下文件的上传的几种方式: 首先我们先补充的一个知识点: 一、请求头ContentType: Con...