Home > Back-end >  printing only equal a's and b's recursively in python
printing only equal a's and b's recursively in python

Time:11-27

I was wondering how to print strings of a's and b's of an equal amount using recursion, for example: if the input is "4", the outputs would be aabb abab bbaa, baba, baab, and abba.

this is what i have so far:

def ab_equal(length, current):
    if length == 0:
        print(current)
    else:
        k = -1
        ab_equal(length - 1, current   "a")
        ab_equal(length - 1, current   "b")


if __name__ == "__main__":
    print(ab_equal(4, " "))

CodePudding user response:

One way is to count a's and b's:

def ab_equal(length, current, a=None, b=None):
    if a is None:
        a = b = length // 2
    if length == 0:
        print(current)
    else:
        if a:
            ab_equal(length - 1, current   "a", a - 1, b)
        if b:
            ab_equal(length - 1, current   "b", a, b - 1)


if __name__ == "__main__":
    ab_equal(4, "")
aabb
abab
abba
baab
baba
bbaa

CodePudding user response:

Something like so would work:

def ab_equal(length, current=""):

    if len(current) == length:
        if current.count("a") == current.count("b"):
            print(current)
    else:
        ab_equal(length, current   "a")
        ab_equal(length, current   "b")


ab_equal(4)
aabb
abab
abba
baab
baba
bbaa

Since we don't have to return (and only print) you can print out at the end the call stack.

  • Related