Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 17447

how does this code work? all balanced permutations from codewars

$
0
0

I met this problem in codewars and I do not understand the solution from other users.

This is the question

Write a function which makes a list of strings representing all of the ways you can balance n pairs of parenthesesExamplesbalanced_parens(0) => [""]balanced_parens(1) => ["()"]balanced_parens(2) => ["()()","(())"]balanced_parens(3) => ["()()()","(())()","()(())","(()())","((()))"]

My solution involves using itertools permutations to get all permutations from input and adding them to a list. However, this will use up too much memory once n gets to 10.

this is the solution from another user.

def balanced_parens(n):'''    To construct all the possible strings with n pairs of balanced parentheses    this function makes use of a stack of items with the following structure:        (current, left, right)    Where:        current is the string being constructed        left is the count of '(' remaining        right is the count of  ')' remaining'''    stack = [('', n, 0)]    result = []    # Loop until we run out of items in the stack    while stack:        current, left, right = stack.pop()        # if no '(' or ')' left to add, add current to the result        if left == 0 and right == 0:            result.append(current)        # if we can, add a '(' and return to the stack        if left > 0:            stack.append((current +'(', left - 1, right + 1))        # if we can, add a ')' and return to the stack        if right > 0:            stack.append((current +')', left, right - 1))    return result

I do not understand how this code will cycle through all permutations.

From my understanding, I know that this code will add a '(' while in the loop, and a ')' when there is an open '('. So n=3 will return '()()()'

But how does it cycle through the rest, eg '((()))'?

i tried looking through the comments for this answer. Other than saying that this is a very elegant solution, not much else was said. I was not able to understand much from chatgpt either.


Viewing all articles
Browse latest Browse all 17447

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>