Advertisement
Guy_Lalonde

Khayyam Triangle

Jul 14th, 2014
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. # Double Gold Star
  2.  
  3. # Khayyam Triangle
  4.  
  5. # The French mathematician, Blaise Pascal, who built a mechanical computer in
  6. # the 17th century, studied a pattern of numbers now commonly known in parts of
  7. # the world as Pascal's Triangle (it was also previously studied by many Indian,
  8. # Chinese, and Persian mathematicians, and is known by different names in other
  9. # parts of the world).
  10.  
  11. # The pattern is shown below:
  12.  
  13. # 1
  14. # 1 1
  15. # 1 2 1
  16. # 1 3 3 1
  17. # 1 4 6 4 1
  18. # ...
  19.  
  20. # Each number is the sum of the number above it to the left and the number above
  21. # it to the right (any missing numbers are counted as 0).
  22.  
  23. # Define a procedure, triangle(n), that takes a number n as its input, and
  24. # returns a list of the first n rows in the triangle. Each element of the
  25. # returned list should be a list of the numbers at the corresponding row in the
  26. # triangle.
  27.  
  28.  
  29. def triangle(n):
  30. result=[]
  31.  
  32. if n==0:
  33. return result
  34. if n>=1:
  35. result.append([1])
  36. if n > 1:
  37. i=2
  38. baseline= [1]
  39. while i <=n:
  40. cache= []
  41.  
  42. baseline.insert(0,0)
  43. baseline.insert(len(baseline),0)
  44. new_baseline=[]
  45. s=0
  46. while s < (len(baseline)-1):
  47. new_baseline.append((baseline[s]+ baseline[s+1]))
  48. s=s+1
  49. # print new_baseline
  50. # cache.append(new_baseline)
  51. result.append(new_baseline[0:])
  52.  
  53. baseline=new_baseline
  54. i = i+1
  55.  
  56. return result
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64. #For example:
  65.  
  66. print triangle(0)
  67. #>>> []
  68.  
  69. print triangle(1)
  70. #>>> [[1]]
  71.  
  72. print triangle(2)
  73. #>> [[1], [1, 1]]
  74.  
  75. print triangle(3)
  76. #>>> [[1], [1, 1], [1, 2, 1]]
  77.  
  78. print triangle(6)
  79. #>>> [[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