From 16a2c25356941fac974bf863878bf73cfe7642a5 Mon Sep 17 00:00:00 2001 From: lolabird Date: Thu, 29 Feb 2024 11:48:18 -0700 Subject: [PATCH] Fix formatting issues for Pascal --- .../Chapter-16-Exercises/Problem13_pascal.py | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/thinkcspy/Chapter-16-Exercises/Problem13_pascal.py b/thinkcspy/Chapter-16-Exercises/Problem13_pascal.py index f196d94..6262852 100644 --- a/thinkcspy/Chapter-16-Exercises/Problem13_pascal.py +++ b/thinkcspy/Chapter-16-Exercises/Problem13_pascal.py @@ -3,13 +3,26 @@ # Problem 13 def createTriangle(numRows): + triangle = [] + if numRows < 0: return else: for i in range(numRows+1): - spaces = (" "*(numRows-i)) - nums = f"{createRow(i)}" - print(spaces + nums) + 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)) def createRow(currentRow): @@ -19,9 +32,7 @@ def createRow(currentRow): coefficient = getbinomial(currentRow, i) row.append(coefficient) - result = " ".join(map(str, row)) - - return result + return row def getbinomial(n, k): numerator = factorial(n)