Leetcode Algorithm No.241 Different Ways to Add Parentheses - 学高手写代码

这篇博客介绍了LeetCode算法题241的不同解决方案,包括使用Python 3.4的方法一和方法二,但这两个方法在运行时遇到AttributeError。此外,文章还强调了enumerate、正则表达式、operator模块和list操作在解决问题中的应用,以及eval函数用于计算字符串表达式的值。虽然方法三也失败了,但文章提供了多个关键知识点供学习者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下方法来自 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值