This question has already been answered:

enter image description here Write a program that checks the correctness of a bracket expression with four kinds of brackets: (), [], {} and <>.

input = '*+/=?^_`{|}~-+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])' brackets = [('(', ')'), ('[', ']'), ('{', '}')] def check(input, brackets): stack = [] for ch in input: for br in brackets: if br[0] == ch: stack.append(ch) break elif br[1] == ch: if stack and br[0] == stack.pop(): break else: return False print(check(input, brackets)) 

Reported as a duplicate by LFC members, Enikeyschik , freim , Sergey Gornostaev python Mar 17 at 8:39 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    Yak, sir, may you also take the laboratory for you? - RiotBr3aker 10:10
  • Ahah it would not be bad) - user330632
  • I just don't understand, so please help) - user330632 10:17 pm
  • Explain at least what kind of bracket expressions? Examples of input / output data. Your attempts to solve, or at least speculation. - froxxendsg
  • Why does not work where the error? - user330632 10:35 pm

1 answer 1

In general, your algorithm works correctly, added only a couple of strokes, so that the function returns True when the open brackets correspond to closed ones, and False when not.

And advice - do not use reserved names as variables and functions, in this case input .

 in_str_correct_0 = '*+/=?^_`{|}~-+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])'; in_str_correct_1 = 'sfadsfdsgafsdf'; in_str_incorrect_0 = '['; in_str_incorrect_1 = '[()[]{}]{[]'; brackets = [('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')]; def check(in_str, brackets): stack = [] for ch in in_str: for br in brackets: if br[0] == ch: stack.append(ch) break elif br[1] == ch: if stack and br[0] == stack.pop(): break else: return False if ( len(stack) == 0 ): return True; else: return False; print(check(in_str_correct_0, brackets)); print(check(in_str_correct_1, brackets)); print(check(in_str_incorrect_0, brackets)); print(check(in_str_incorrect_1, brackets)); 

Conclusion:

 True True False False 
  • I don’t know python, so I can be wrong, but is this for br in brackets: n’t linear search? Probably, it would be better to store brackets as a hashset, and not an array? - tym32167