以下方法来自 Leetcode Discuss
Python version is 3.4
方法一
''' 跟着高手写python '''
import re
def diffWaysToCompute(self, input):
tokens = re.split('(\D)', input)
'''
map 的使用还不是很清楚,并且报错TypeError: object of type 'map' has no len()
故不使用map, 直接让nums 中保持type 为 char, 用eval 进行运算
'''
#nums = map(int, tokens[::2])
#nums = [int(i) for i in tokens[::2]]
nums = tokens[::2]
''' nums = [2, 3, 4, 5] '''
#ops = map({'+':operator.add, '-':operator.sub, '*':operator.mul}.get,tokens[1::2])
ops = tokens[1::2]
''' ops = ['*', '-', '*'] '''
def build(lo,hi):
if lo == hi:
return [nums[lo]]
''' 此处换为用eval 作计算 '''
#return [ops[i](a,b)
return [str(eval(a+ops[i]+b))
for i in range(lo,hi)
for a in build(lo,i)
for b in build(i+1,hi)]
return [int(num) for num in build(0,len(ops))]
'''
build 函数的思想类似于 nums = [int(i) for i in tokens[::2]],在赋值的同时完成循环,
'''
#s="0"
s="2*3-4*5"
#s='2-1-1'
self = []
a=diffWaysToCompute(self,s)
'''
['-34', '-10', '-14', '-10', '10']
'''
纯净版
def diffWaysToCompute(self, input):
tokens = re.split('(\D)', input)
nums = tokens[::2]
''' nums = [2, 3, 4, 5] '''
#ops = map({'+':operator.add, '-':operator.sub, '*':operator.mul}.get,tokens[1::2])
ops = tokens[1::2]
''' ops = ['*', '-', '*'] '''
def build(lo,hi):
if lo == hi:
return [nums[lo]]
''' 此处换为用eval 作计算 '''
#return [ops[i](a,b)
return [str(eval(a+ops[i]+b))
for i in range(lo,hi)
for a in build(lo,i)
for b in build(i+1,hi)]
return [int(num) for num in build(0,len(ops))]
方法二
def diffWaysToCompute(self, input):
return [eval(a+c+b)
for i, c in enumerate(input) if c in '+-*'
for a in self.diffWaysToCompute(input[:i])
for b in self.diffWaysToCompute(input[i+1:])] or [int(input)]
测试数据:
s="2*3-4*5" #s='2-1-1' self = [] a=diffWaysToCompute(self,s) |
不能运行,报错AttributeError: 'list' object has no attribute 'diffWaysToCompute'
方法三
def diffWaysToCompute(self, input):
return [a+b if c == '+' else a-b if c == '-' else a*b
for i, c in enumerate(input) if c in '+-*'
for a in self.diffWaysToCompute(input[:i])
for b in self.diffWaysToCompute(input[i+1:])] or [int(input)]
同样不能运行,报错AttributeError: 'list' object has no attribute 'diffWaysToCompute'
知识点:
1. enumerate 的用法
以下官方定义:
enumerate (iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration.
>>> s=[1,2,3] >>> a=enumerate(s) >>> a <enumerate object at 0x03AD5148> >>> list(a) [(0, 1), (1, 2), (2, 3)] |
2. import re -- 如果要使用正则表达式,需要导入re 模块
下面的例子用一个正则表达式指定分割规则:
>>>re.split('(\D)', "2*3-4*5")
输出为 ['2', '*', '3', '-', '4', '*', '5']
3. operator 模块是一个做四则运算的库。用法如下:
operator.add(x, y) = x+y
相应的还有 operator.sub , operator.mul 等
4. list 的妙用, tokens = ['2', '*', '3', '-', '4', '*', '5']
>>> tokens[::2]
输出为 ['2', '3', '4', '5']
5. eval 函数用于计算一个表达式(字符串)的值
>>> eval('1+3')
输出为 4