当前位置:网站首页>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
边栏推荐
猜你喜欢
Mobile note application
Operations related to sequence table
Chapter 14 signals (IV) - examples of multi process tasks
第十四章 信号(四)- 多进程任务示例
【脑洞大开】《西潮》及《走向世界丛书》
用.Net Core接入微信公众号开发
[datawhale202206] pytorch recommendation system: recall model DSSM & youtubednn
redis探索之缓存一致性
ROS2 Foxy depthai_ros教程
Sort out relevant contents of ansible
随机推荐
[Maui] add click events for label, image and other controls
AI matting tool
Circular linked list--
[Suanli network] technological innovation of Suanli Network -- key technology of operation service
腾讯安全发布《BOT管理白皮书》|解读BOT攻击,探索防护之道
R语言使用yardstick包的conf_mat函数计算多分类(Multiclass)模型在每个交叉验证(或者重采样)的每一折fold上的混淆矩阵、并使用summary输出每个fold的其它详细指标
Digital signal processing -- Design of linear phase (Ⅱ, Ⅳ) FIR filter (2)
ASTM D 3801 vertical burning test of solid plastics
数字信号处理——线性相位型(Ⅱ、Ⅳ型)FIR滤波器设计(2)
ROS2 Foxy depthai_ros教程
《MATLAB 神经网络43个案例分析》:第40章 动态神经网络时间序列预测研究——基于MATLAB的NARX实现
简单斐波那契(递推)
華為面試題: 招聘
First intention is the most important
腾讯黎巍:深耕“监管科技”,护航数字经济行稳致远
Ansi/ul 94 VTM vertical burning test for thin materials
[20220605] Literature Translation -- visualization in virtual reality: a systematic review
QT 播放器之列表[通俗易懂]
第十四章 信号(四)- 多进程任务示例
What are the PHP FPM configuration parameters