PEP 8
The Style Guide for Python Code has many recommendations that all Python programs should follow. These include:
snake_case
for variable and function names, instead of bumpyWords
. As such, heightOfTriangle
should be height_of_triangle
, or perhaps less verbose triangle_height
- no spaces in list slices.
lstOfCoefficients[0 : i]
should be lstOfCoefficients[0:i]
Unused variables
powerOf2
is unused, and can be safely removed.
Logical thoughts should be grouped
You have print(" " * (heightOfTriangle - i), end="")
to print several blanks at the start of an output line. Then, you have 8 lines of code where calculations are done for the row coefficients. Then, you continue with the printing.
Your code would be more understandable if you did all your printing in one spot. The indentation print statement could sit just above for j ...
Use functions
Using function helps separate your code into logical blocks. Here, you have user input and program output all mashed together. If the Pascal triangle printing code was in its own function, you could call it after getting the user input. The function would logically contain its own variables, like the height of the triangle, but since we'd be inside a "Pascal's triangle" function, you could just name it height
for brevity without loss of clarity.
Efficiency
After you generate 1 5 10 10 5 1
, the row is computed by adding 1+5
, 5+10
, 10+10
, 10+5
, and 5+1
, inserting these at the appropriate positions. This gives you:
[1, 6, 15, 20, 15, 6, 5, 10, 10, 5, 1]
What is all that "fluff" doing at the end of the list? That exists because you are inserting the values into the previous row, making the row about twice as long as the previous row. You then trim off all the fluff with ...
lstOfCoefficients[0 : i]
and then you are ...
+ lstOfCoefficients[(len(lstOfCoefficients) - 1): len(lstOfCoefficients)]
... which is a very verbose way of add a list of just the last element. You can state this much simpler using negative indexing like lstOfCoefficients[-1:]
. Of course, we know the last element is always a one, so you could also simply use + [1]
.
Instead of inserting, causing the list to double in length, you could simply overwrite the previous values, and then simply append the final 1
.
for k in range(i - 1):
lstOfCoefficients[k + 1] = lst[k] + lst[k + 1]
lstOfCoefficients.append(1)
Reworked code
def print_pascals_triangle(height):
coefficients = [1]
for row_num in range(height):
print(" " * (height - row_num), *coefficients)
# Compute next row
previous = coefficients[:]
for k in range(row_num):
coefficients[k + 1] = previous[k] + previous[k + 1]
coefficients.append(1)
print_pascals_triangle(int(input()))
Note: print(*coeff)
is like saying print(coeff[0], coeff[1], coeff[2], ...)
with all the elements of the list exploded out as separate arguments. Since Python prints out the arguments separated by spaces by default, the printing is done in a single statement.