There is a Boolean expression string as below. I want to recognize the parentheses here and get what's in the innermost parentheses.
(((x12 & x20) & x05) | x02) | ((x12 & x13)) | (x13 | x20)
Result: (x12 & x20)
python
>>> s = '(((x12 & x20) & x05) | x02) | ((x12 & x13)) | (x13 | x20)'
>>> Answer = ''
>>> Depth = 0
>>> Highest Depth = 0
>>> for c in s:
if c == '(':
Depth += 1
Node string = ''
elif c == ')':
print('--'* depth, node string)
If Depth > Maximum Depth:
Maximum depth = depth
Answer = Node string
Depth - = 1
else:
Node string += c
------ ------ x12 & x20
---- ---- x12 & x20 & x05
-- -- x12 & x20 & x05 | x02
---- ---- x12 & x13
-- -- x12 & x13
-- -- x13 | x20
>>> Answer
'x12 & x20'
>>>
There is also a way to search (depth priority) like the upper section, but you can use Python's ast module. Ast is the best tool for something substantial (e.g., source analysis).
https://python-ast-explorer.com/
© 2024 OneMinuteCode. All rights reserved.