📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division1213# here is a mostly-straightforward solution to the14# two-by-two version of the grid.1516def do_twice(f):17f()18f()1920def do_four(f):21do_twice(f)22do_twice(f)2324def print_beam():25print('+ - - - -', end=' ')2627def print_post():28print('| ', end=' ')2930def print_beams():31do_twice(print_beam)32print('+')3334def print_posts():35do_twice(print_post)36print('|')3738def print_row():39print_beams()40do_four(print_posts)4142def print_grid():43do_twice(print_row)44print_beams()4546print_grid()474849# here is a less-straightforward solution to the50# four-by-four grid5152def one_four_one(f, g, h):53f()54do_four(g)55h()5657def print_plus():58print('+', end=' ')5960def print_dash():61print('-', end=' ')6263def print_bar():64print('|', end=' ')6566def print_space():67print(' ', end=' ')6869def print_end():70print()7172def nothing():73"do nothing"7475def print1beam():76one_four_one(nothing, print_dash, print_plus)7778def print1post():79one_four_one(nothing, print_space, print_bar)8081def print4beams():82one_four_one(print_plus, print1beam, print_end)8384def print4posts():85one_four_one(print_bar, print1post, print_end)8687def print_row():88one_four_one(nothing, print4posts, print4beams)8990def print_grid():91one_four_one(print4beams, print_row, nothing)9293print_grid()9495comment = """96After writing a draft of the 4x4 grid, I noticed that many of the97functions had the same structure: they would do something, do98something else four times, and then do something else once.99100So I wrote one_four_one, which takes three functions as arguments; it101calls the first one once, then uses do_four to call the second one102four times, then calls the third.103104Then I rewrote print1beam, print1post, print4beams, print4posts,105print_row and print_grid using one_four_one.106107Programming is an exploratory process. Writing a draft of a program108often gives you insight into the problem, which might lead you to109rewrite the code to reflect the structure of the solution.110111--- Allen112"""113114print(comment)115116117