python_exercises/thinkcspy/Chapter-16-Exercises/Problem13_pascal.py

56 lines
1.1 KiB
Python
Raw Permalink Normal View History

# Runestone.Academy thinkcspy course
# Chapter 16
# Problem 13
def createTriangle(numRows):
2024-02-29 11:48:18 -07:00
triangle = []
2023-12-22 06:15:34 -07:00
if numRows < 0:
2023-12-22 02:23:49 -07:00
return
2023-12-22 04:02:11 -07:00
else:
2023-12-22 06:15:34 -07:00
for i in range(numRows+1):
2024-02-29 11:48:18 -07:00
triangle.append(createRow(i))
lastRow = triangle[-1]
numWidth = len(str(max(lastRow))) + 1
triWidth = numWidth * len(lastRow)
for row in triangle:
triStr = ""
for num in row:
numStr = str(num)
triStr += numStr + " " * (numWidth - len(numStr))
print(triStr.center(triWidth))
2023-12-22 04:02:11 -07:00
2023-12-22 06:15:34 -07:00
def createRow(currentRow):
row = []
for i in range(currentRow + 1):
coefficient = getbinomial(currentRow, i)
row.append(coefficient)
2024-02-29 11:48:18 -07:00
return row
2023-12-22 06:15:34 -07:00
def getbinomial(n, k):
numerator = factorial(n)
denominator = factorial(k) * factorial(n - k)
return numerator // denominator
def factorial(number):
if number < 0:
return
elif number > 1:
number *= factorial(number - 1)
return number
else:
return 1
2023-12-22 04:02:11 -07:00
2023-12-22 02:23:49 -07:00
createTriangle(10)
2023-12-22 02:23:49 -07:00