Imagine a function print_street_at_height(elements, height)
that produces a single line of output: the street at the specified height. For example, again consider this street, with heights shown in a column on the right:
height +-------------------------------+ | | 7 | xxxxx | 6 | xxxxx | 5 | * xxxxx | 4 | *** xxxxx | 3 | ***** xxxxx | 2 | | xxxxx | 1 | | xxxxx ~ ~ | 0 +-------------------------------+The call
print_street_at_height(..., 0)
would print this line:
| | xxxxx ~ ~ |The call
print_street_at_height(..., 2)
would print this line:
| ***** xxxxx |Thus, calling
print_street_at_height
with a series of descending heights would produce the rendering, excluding the top and bottom borders.
Now imagine that there are three classes that represent the bulding, park, and empty lot elements of a street. The classes are called Building
, Park
, and EmptyLot
, respectively. Each class has an at_height
method that returns a string that is the text for that element at the specified height. Example: (blank lines added for clarity)
>>> b = Building(3,4,"x") # NOTE: this is not the same building that's shown above! >>> b.at_height(0) 'xxx' >>> b.at_height(4) ' '
Next, consider this:
>>> s = [EmptyLot(5,"_"), Building(3,4,"x"), Park(7,"*")] >>> h = 0 >>> s[0].at_height(h) + s[1].at_height(h) + s[2].at_height(h) ' xxx | ' >>> h = 2 >>> s[0].at_height(h) + s[1].at_height(h) + s[2].at_height(h) ' xxx ***** '
Combining the ideas of (1) and (2) leads to this:
>>> s = [EmptyLot(5,"_"), Building(3,4,"x"), Park(7,"*")] >>> print_street_at_height(s, 5) >>> print_street_at_height(s, 4) * >>> print_street_at_height(s, 3) xxx *** >>> print_street_at_height(s, 2) xxx ***** >>> print_street_at_height(s, 1) xxx | >>> print_street_at_height(s, 0) xxx |
Note: The version of print_street_at_height
used above output a newline after the text to make for a clear example but in practice you may find that having print_street_at_height
output a newline creates problems.