Search code examples
pythonrecursion

Recursive approach to triangle pattern printing


I have been learning concepts like recursion lately and tried attempting old programs in python that I solved using an iterative approach for example printing triangular patterns, for example:

*
**
***
****
*****

but the output I get is:

*****
****
*** 
**  
*   
None
def itriangle(x):
    if x==0:
        return
    print("*",end="")
    itriangle(x-1)
def jtriangle(y):
    if y==0:
        return
    itriangle(y)
    print()
    jtriangle(y-1)
print(jtriangle(5))

this is the code I wrote, Firstly I get this triangle inverted and secondly I get a "None" return as the last line. How to fix this?

Edit: I have fixed the None that I was getting , that was just a typo on my side but now the problem (The main issue) is that I am getting an inverted triangle and dont know how to fix it. any help will be much appreciated.


Solution

  • Recursion can be confusing. I use natural language to make sure I write recursive programs correctly. I can say:

    To print a triangle of size n, first print a triangle of size n-1, then print a line of size n.

    Then convert it directly into code:

    def triangle(n):
        if n==0:
            return
        triangle(n-1)
        print()
        line(n)
    

    Note: names like jtriangle and itriangle don't convey the meaning well. They only serve to confuse you, and recursion is already confusing enough, so use meaningful names instead!


    Another powerful technique I use when developing recursive programs (actually always, but it's especially helpful when using recursion): use bottom-up development! That is, make sure your lower-level functions really work and are free of bugs, before developing your upper-level functions.

    In my example above, make sure the line function works well before writing code for the triangle function. If you have bugs in lower-level functions, recursion will mess you up, and it will be much harder to debug.