How to print pascal triangle using python

Code is below

def pascal(p):
    res = [[0 for i in range(p)] for i in range(p)]
    for i in range(p):
        res.append((11**i))
    return res
p= 3
pascal(p)

My out is [[0, 0, 0], [0, 0, 0], [0, 0, 0], 1, 11, 121]

Expected is

[[1, 0, 0], [1, 1, 0], [1, 2, 1]]

pascal’s triangle is multiplication of 11, will split() method will work here

Answer

You

  • don’t need the array initialization
  • you need to build a value padded with zeros until the size of p
  • split string on each char => list('abcd') == ['a', 'b', 'c', 'd']
def pascal(p):
    res = []
    for i in range(p):
        row = str(11 ** i).ljust(p, '0')
        res.append(list(row))
    return res

print(pascal(3))  
# [['1', '0', '0'], ['1', '1', '0'], ['1', '2', '1']]
print(pascal(6))
# [['1', '0', '0', '0', '0', '0'],
#  ['1', '1', '0', '0', '0', '0'],
#  ['1', '2', '1', '0', '0', '0'],
#  ['1', '3', '3', '1', '0', '0'],
#  ['1', '4', '6', '4', '1', '0'],
#  ['1', '6', '1', '0', '5', '1']]

The list-comprehension equivalent

def pascal(p):
    return [list(str(11 ** i).ljust(p, '0')) for i in range(p)]