Problem: Print Pascal's triangle for a given n.
Example: n = 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Hint: An element in a given row is sum of adjacent elements in the previous row, example, 4 in row 5 is sum of 1 and 3 from row 4.
Solution in Python:
import math
def pascal_triangle(n):
"""
Author: Mayur P Srivastava
"""
row = []
for i in range(n):
new_row = []
for j in range(i+1):
col1 = j - 1
col2 = j
value = 0
if col1 >= 0 and col1 < len(row):
value += row[col1]
if col2 >= 0 and col2 < len(row):
value += row[col2]
if value == 0:
value = 1
new_row.append(value)
row = new_row
print format_row(row, i+1, n)
def format_row(row, row_number, n, max_element_len=4):
offset = int(math.floor((n - row_number) / 2))
element_pattern = "%%%ds " % max_element_len
row_str = ""
for i in range(offset+1):
row_str += element_pattern % ""
for element in row:
row_str += element_pattern % element
return row_str
Concepts learned: Nested loops.
No comments:
Post a Comment