# 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): next_triangle=[] if n==0: return [] if n==1: return [[1]] else: next_triangle=[1]*n old_triangle = triangle(n-1)[len(triangle(n-1))-1] for i in range(1,n-1): next_triangle[i]=old_triangle[i]+old_triangle[i-1] return triangle(n-1)+[next_triangle] #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]]
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question