Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Double Gold Star
- # 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):
- result=[]
- if n==0:
- return result
- if n>=1:
- result.append([1])
- if n > 1:
- i=2
- baseline= [1]
- while i <=n:
- cache= []
- baseline.insert(0,0)
- baseline.insert(len(baseline),0)
- new_baseline=[]
- s=0
- while s < (len(baseline)-1):
- new_baseline.append((baseline[s]+ baseline[s+1]))
- s=s+1
- # print new_baseline
- # cache.append(new_baseline)
- result.append(new_baseline[0:])
- baseline=new_baseline
- i = i+1
- return result
- #For example:
- print triangle(0)
- #>>> []
- print triangle(1)
- #>>> [[1]]
- print triangle(2)
- #>> [[1], [1, 1]]
- print triangle(3)
- #>>> [[1], [1, 1], [1, 2, 1]]
- print triangle(6)
- #>>> [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement