Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursion Function that prints all possible binary permutations

I am trying to write a recursive function that generates all binary permutations with a given input of the amount of ‘A’ and ‘B’ elements that a string should have. For example function(a, b) when a = 2 and b = 2 should generate:
AABB
ABAB
ABBA
BAAB
BABA
BBAA
Would appreciate your help. Thanks!.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The base case is the one where either a or b is zero, since there’s only one permutation if you only have one element. From there, the recursive call just needs to subtract one from either a or b to ensure that they will both eventually reach zero.

>>> def ab(a, b):
...     if not a:
...         return ["B" * b]
...     if not b:
...         return ["A" * a]
...     return ["A" + p for p in ab(a - 1, b)] + ["B" + p for p in ab(a, b - 1)]
...
>>> ab(2, 2)
['AABB', 'ABAB', 'ABBA', 'BAAB', 'BABA', 'BBAA']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading