当前位置:网站首页>leetcode:241. 为运算表达式设计优先级【dfs + eval】
leetcode:241. 为运算表达式设计优先级【dfs + eval】
2022-07-01 12:35:00 【白速龙王的回眸】

分析
每次选择其中的a ? b进行加一对括号
知道用完所有运算符
然后放入一个set中防止运算式子相等即可
ac code
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
ans = []
operators = ('+', '-', '*')
def countOperator(s):
cnt = 0
for c in s:
if c in operators:
cnt += 1
return cnt
s = set()
def dfs(nums, ops):
if len(nums) == 1:
s.add(nums[0])
return
# 选一个进行计算
for i in range(len(nums) - 1):
new_num = '(' + nums[i] + ops[i] + nums[i + 1] + ')'
new_nums = nums[:i] + [new_num] + nums[i + 2:]
new_ops = ops[:i] + ops[i + 1:]
dfs(new_nums, new_ops)
# pattern要按ascii码
nums = re.split('[*+-]', expression)
ops = []
for c in expression:
if c in operators:
ops.append(c)
dfs(nums, ops)
return [eval(exp) for exp in s]
总结
dfs来选可以选的地方
re.split来区分符号和数字,主要要根据ascii码的顺序
然后最后通过eval计算所有不同式子的结果即可
边栏推荐
- 【20211129】Jupyter Notebook遠程服務器配置
- 腾讯黎巍:深耕“监管科技”,护航数字经济行稳致远
- Perl 5.10.0 installation package download
- How to use opcache, an optimization acceleration component of PHP
- Using burpsuite to capture app packages
- AI matting tool
- Mysql database knowledge collation
- Zero copy technology of MySQL
- 顺序表有关操作
- [Suanli network] technological innovation of Suanli Network -- key technology of operation service
猜你喜欢

Switch basic experiment

Share several tools for designing exquisite circuit diagrams

What are the PHP FPM configuration parameters

Typora adds watermarks to automatically uploaded pictures

手机便签应用

《MATLAB 神经网络43个案例分析》:第40章 动态神经网络时间序列预测研究——基于MATLAB的NARX实现

"Analysis of 43 cases of MATLAB neural network": Chapter 40 research on prediction of dynamic neural network time series -- implementation of NARX based on MATLAB

Sort out relevant contents of ansible

Chained storage of queues

【历史上的今天】7 月 1 日:分时系统之父诞生;支付宝推出条码支付;世界上第一支电视广告
随机推荐
【脑洞大开】《西潮》及《走向世界丛书》
【datawhale202206】pyTorch推荐系统:召回模型 DSSM&YoutubeDNN
ASTM D 3801 vertical burning test of solid plastics
Onenet Internet of things platform - mqtt product equipment upload data points
手机便签应用
使用nvm管理nodejs(把高版本降级为低版本)
ASTM D 3801固体塑料垂直燃烧试验
关于NAND FLASH解扣的认识
IOS interview
GID:旷视提出全方位的检测模型知识蒸馏 | CVPR 2021
Zero copy technology of MySQL
题目 1004: 母牛的故事(递推)
Stack-------
AI matting tool
手把手教你完成图像分类实战——基于卷积神经网络的图像识别
腾讯安全联合毕马威发布监管科技白皮书,解析“3+3”热点应用场景
VS Code 设置代码自动保存
Compile and debug net6 source code
Digital signal processing -- Design of linear phase (Ⅱ, Ⅳ) FIR filter (2)
[20211129] jupyter notebook remote server configuration