Python program to check matching of simple parentheses

后端 未结 25 2409
谎友^
谎友^ 2020-12-01 17:02

I am a Python newbie and I came across this exercise of checking whether or not the simple brackets \"(\", \")\" in a given string are matched evenly.

I have seen ex

25条回答
  •  醉话见心
    2020-12-01 17:24

    You can do this in a couple of lines using accumulate (from itertools). The idea is to compute a cumulative parenthesis level going through the string with opening parentheses counting as level+1 and closing parentheses counting as level-1. If, at any point, the accumulated level falls below zero then there is an extra closing parenthesis. If the final level is not zero, then there is a missing closing parenthesis:

    from itertools import accumulate
    def matched(s):
        levels = list(accumulate((c=="(")-(c==")") for c in s))
        return all( level >= 0 for level in levels) and levels[-1] == 0
    

提交回复
热议问题