Python
Programming Exercises,
Gently Explained
89
Solution Design
It’s important to notice the general pattern as the height of the pyramid increases. Here’s a
pyramid of height 1:
#
Here’s a pyramid of height 2:
#
###
Here’s a pyramid of height 3:
#
###
#####
In order to center the pyramid correctly, you need to print
the correct amount of space
characters on the left side of the row. Here’s the pyramid with height set to 5 and the spaces
marked with periods to make them visible:
....#
...###
..#####
.#######
#########
The number of hashtag characters begins at 1 for the top row and then increases by 2. The code
in the for loop requires a number of hashtags equal to rowNumber * 2 + 1.
The following table
shows the number of spaces and hashtags for a pyramid of height 5:
Row Number
Number of Spaces
Number of Hashtags
0
4
1
1
3
3
2
2
5
3
1
7
4
0
9
Notice that for all pyramids, the number of spaces for the top row is height - 1, and each
subsequent row has one less space than the previous row. An easier way to create each row is with a
for
loop that ranges from 0 up to, but
not including, height for the row number, where row 0 is at
the top. Then the number of spaces at a row number is height – (rowNumber + 1).
String replication can easily create the # hashtag and space character strings. In Python, you can
use the * operator with a string and an integer to evaluate to a longer string. For example,
enter the
following into the interactive shell:
>>> 'Hello' * 3
'HelloHelloHello'
>>> '#' * 7
'#######'
Python Programming Exercises, Gently Explained
90
>>> rowNumber = 5
>>> (rowNumber * 2 + 1) * '#'
'###########'
Dostları ilə paylaş: