MCPcopy Create free account
hub / github.com/asweigart/PythonStdioGames / main

Function main

src/gamesbyexample/matchingparens.py:6–34  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

4Tags: short, algorithm"""
5__version__ = 0
6def main():
7 print('''Matching Parentheses Algorithm
8 By Al Sweigart al@inventwithpython.com
9
10 This demonstrates an algorithm for detecting matching parentheses,
11 curly braces, and square brackets in a string. For example:
12
13 MATCHING NOT MATCHING
14 () )(
15 {}[] [[]
16 ({[]}) ({)}
17 {[][](())} {}}
18
19 The algorithm works by using a "stack" data structure, where values
20 are only added or removed from the "top" of the stack.
21
22 To check a string, we loop over each symbol in order. Opening
23 symbols are "pushed" (added) to the stack, while closing symbols
24 "pop" (remove) the symbol off of the stack (but only if it's matches
25 the opening symbol at the top of the stack.)
26 The string has matching parentheses/braces/brackets if the stack is
27 empty at the end of the string.
28 ''')
29 print('Enter the string to check, for example {[][](())}:')
30 response = input('> ')
31 print()
32
33 result = isMatchingParens(response)
34 print('"' + response + '"', 'IS MATCHING:', result)
35
36
37def isMatchingParens(strToCheck):

Callers 1

matchingparens.pyFile · 0.70

Calls 1

isMatchingParensFunction · 0.85

Tested by

no test coverage detected