Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Last active June 1, 2017 18:20
Show Gist options
  • Save Per48edjes/f95378e4aea6c52fe84704b38c901087 to your computer and use it in GitHub Desktop.
Save Per48edjes/f95378e4aea6c52fe84704b38c901087 to your computer and use it in GitHub Desktop.
Using recursion to generate list form of Pascal's Triangle
# Khayyam Triangle
# The French mathematician, Blaise Pascal, who built a mechanical computer in
# the 17th century, studied a pattern of numbers now commonly known in parts of
# the world as Pascal's Triangle (it was also previously studied by many Indian,
# Chinese, and Persian mathematicians, and is known by different names in other
# parts of the world).
# The pattern is shown below:
# 1
# 1 1
# 1 2 1
# 1 3 3 1
# 1 4 6 4 1
# ...
# Each number is the sum of the number above it to the left and the number above
# it to the right (any missing numbers are counted as 0).
# Define a procedure, triangle(n), that takes a number n as its input, and
# returns a list of the first n rows in the triangle. Each element of the
# returned list should be a list of the numbers at the corresponding row in the
# triangle.
def triangle(n):
if n == 0:
return []
if n == 1:
return [[1]]
if n > 1 :
old_triangle = triangle(n-1)
previous_row = old_triangle[-1]
middle_nums = []
for i in range(0,n-2):
temp = previous_row[i] + previous_row[i+1]
middle_nums.append(temp)
last_row = [1] + middle_nums + [1]
return old_triangle + [last_row]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment