Search code examples
pythonrecursionpascals-triangle

Explain the working of this pascal's algorithm


                  1

                1    1

             1     2     1

          1     3     3     1

       1     4     6     4     1

    1     5     10    10     5    1
def pascal(n):
    if n == 1:
        return [1]
    else:
        line = [1]
        previous_line = pascal(n-1)
        print(previous_line)
        for i in range(len(previous_line)-1):
            line.append(previous_line[i] + previous_line[i+1])
        line += [1]
    return line

print(pascal(4))

previous_line = pascal(n-1) I didn't get this line along with that for loop pascal(n-1) returns an integer and how come we can use len function over that integer in for loop


Solution

  • pascal(n-1) doesn't return a number, it returns a list. For example pascal(4-1) returns the list [1, 2, 1]. Then, you use len to get the length of that list. Given that length, you create a loop over i to find the sums of elements i and i+1 of that list. Then, you append that sum to the new list you are creating.

    To get the triangle as in the example image, you need some small adaptions:

    def pascal(n, indent=""):
        line = [1]
        if n > 1:
            previous_line = pascal(n-1, indent+"  ")
            for i in range(len(previous_line)-1):
                line.append(previous_line[i] + previous_line[i+1])
            line += [1]
        print(indent + "".join([f'{i:4}' for i in line]))
        return line
    
    pascal(6)