Home > Enterprise >  Recursion Function that prints all possible binary permutations
Recursion Function that prints all possible binary permutations

Time:05-20

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!.

CodePudding user response:

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']
  • Related