-2
                  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

Henry Harutyunyan
  • 2,355
  • 1
  • 16
  • 22
Alpha
  • 9
  • 3

2 Answers2

0

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)
JohanC
  • 71,591
  • 8
  • 33
  • 66
0

Just in case you're looking for a simpler answer:

ROWS = 5

def row( a, b ) :
   return ' ' * (b-a-1) + ' '.join([i for i in str(11**a)])

for i in range(ROWS) :
    print row( i, ROWS )

outputs:

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

and if you want this to work in python3, add parentheses in print( .. ) call.

lenik
  • 23,228
  • 4
  • 34
  • 43