Python 3, how to get the contents in the innermost parentheses in the string with parentheses ()

Asked 2 years ago, Updated 2 years ago, 17 views

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

2022-09-22 19:31

2 Answers

>>> 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'
>>> 


2022-09-22 19:31

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://medium.com/simply-scaled/what-s-an-abstract-syntax-tree-ast-how-to-turn-your-python-code-into-one-and-why-you-should-81d6334c1c0f

https://python-ast-explorer.com/


2022-09-22 19:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.