Advertisement
asweigart

Balanced Parens Python

Jun 11th, 2021
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. def getBalancedParens(pairs, openRem=None, closeRem=None, current='', indent=0):
  2. if openRem is None:
  3. openRem = pairs
  4. if closeRem is None:
  5. closeRem = pairs
  6.  
  7. print('.' * indent, end='')
  8. print('Start of pairs=' + str(pairs) + ', openRem=' + str(openRem) + ', closeRem=' + str(closeRem) + ', current="' + current + '"')
  9. if openRem == 0 and closeRem == 0:
  10. # BASE CASE
  11. print('.' * indent, end='')
  12. print('1st base case. Returning ' + str([current]))
  13. return [current]
  14.  
  15. # RECURSIVE CASE
  16. results = []
  17. if openRem > 0:
  18. print('.' * indent, end='')
  19. print('Adding open parenthesis.')
  20. results.extend(getBalancedParens(pairs, openRem - 1, closeRem, current + '(', indent + 1))
  21. if closeRem > openRem:
  22. print('.' * indent, end='')
  23. print('Adding close parenthesis.')
  24. results.extend(getBalancedParens(pairs, openRem, closeRem - 1, current + ')', indent + 1))
  25.  
  26. # BASE CASE
  27. print('.' * indent, end='')
  28. print('2nd base case. Returning ' + str(results))
  29. return results
  30.  
  31. print('All combinations of 3 balanced parentheses:')
  32. print('Results:', getBalancedParens(3))
  33.  
  34.  
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement