当前位置:网站首页>leetcode:241. Design priority for operation expression [DFS + Eval]
leetcode:241. Design priority for operation expression [DFS + Eval]
2022-07-01 12:36:00 【White speed Dragon King's review】

analysis
Choose one of them every time a ? b Add a pair of parentheses
Know to run out of all operators
Then put in a set It is enough to prevent the expressions from being equal
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
# Choose one to calculate
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 To press ascii code
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]
summary
dfs Choose the place you can choose
re.split To distinguish between symbols and numbers , Mainly based on ascii The order of the codes
And then finally through eval Calculate the results of all the different formulas
边栏推荐
- JS reverse | m3u8 data decryption of a spring and autumn network
- MySQL workbench data modeling function
- 华为面试题: 招聘
- Sleep quality today 79 points
- Need your own cognition
- 网络socket的状态要怎么统计?
- Like the three foot platform
- Ansible相关内容梳理
- Interpretation of hard threshold function [easy to understand]
- Arm GIC (V) how arm TrustZone supports security interrupt analysis notes.
猜你喜欢

Double linked list related operations

Onenet Internet of things platform - mqtt product devices send messages to message queues MQ

用.Net Core接入微信公众号开发

Onenet Internet of things platform - mqtt product equipment upload data points

Arm GIC (V) how arm TrustZone supports security interrupt analysis notes.

Mobile note application

2022-06-28-06-29

ROS2 Foxy depthai_ros教程

MySQL common functions

Chained storage of queues
随机推荐
ANSI/UL 94 VTM薄质材料垂直燃烧测试
AI matting tool
Ansible Playbook
题目 1004: 母牛的故事(递推)
栈的应用——括号匹配问题
类的初始化与实例化
第十四章 信号(四)- 多进程任务示例
kubernetes之ingress探索实践
ASTM D 3801 vertical burning test of solid plastics
2022-06-28-06-29
[106] 360 check font - check whether the copyright of local Fonts is commercially available
IOS interview
[20220605] Literature Translation -- visualization in virtual reality: a systematic review
【邂逅Django】——(二)数据库配置
ROS2 Foxy depthai_ros教程
CPI tutorial - asynchronous interface creation and use
腾讯安全联合毕马威发布监管科技白皮书,解析“3+3”热点应用场景
R语言基于h2o包构建二分类模型:使用h2o.gbm构建梯度提升机模型GBM、使用h2o.auc计算模型的AUC值
Tencent security released the white paper on BOT Management | interpreting BOT attacks and exploring ways to protect
Eurake partition understanding