I have coded a solution to build all valid permutations of parentheses.
My code is below.
I have a question on my code based on a comment by my PEP8 checker. It said that there was no need to include the line return
anywhere in the code (initially I included one). The solution works but I have never had a case using recursion where I didn't have to use the return
line in the base-case.
How come I don't need it here?
The following expression initially had a return
statement but I was told this was obsolete.
if number_open == number_pairs and number_closed == number_pairs:
print(output)
build_parentheses.counter += 1
return
Python 3.7 code:
"""Module builds all valid permutations of n parentheses
For example: n = 3:
((()))
(()())
(())()
()(())
()()()
Total = 5
"""
def build_parentheses(number_pairs: int,
output="",
number_open=0,
number_closed=0)-> str:
"""The function that builds the parentheses. Output as a string:
number_pairs: number of parentheses pairs user desired
All other parameters are private
"""
if number_open == number_pairs and number_closed == number_pairs:
print(output)
build_parentheses.counter += 1
else:
if number_open < number_pairs:
output += "("
build_parentheses(number_pairs, output, number_open + 1, number_closed)
output = output[:-1]
if number_closed < number_open and number_open:
output += ")"
build_parentheses(number_pairs, output, number_open, number_closed + 1)
if __name__ == "__main__":
build_parentheses.counter = 0
build_parentheses(5)
print(f"=========\n{build_parentheses.counter} solutions")
By comparison, in this post I made, I did use the return statement.
return
statement? \$\endgroup\$build_parentheses.counter += 1
in the base-caseif....
\$\endgroup\$else:
block here, rendering thereturn
obsolete. \$\endgroup\$else
, there is no more reachable code detected. If you have more questions about the scope of code blocks, take it to chat :) \$\endgroup\$