Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96168
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
# here is a mostly-straightforward solution to the
15
# two-by-two version of the grid.
16
17
def do_twice(f):
18
f()
19
f()
20
21
def do_four(f):
22
do_twice(f)
23
do_twice(f)
24
25
def print_beam():
26
print('+ - - - -', end=' ')
27
28
def print_post():
29
print('| ', end=' ')
30
31
def print_beams():
32
do_twice(print_beam)
33
print('+')
34
35
def print_posts():
36
do_twice(print_post)
37
print('|')
38
39
def print_row():
40
print_beams()
41
do_four(print_posts)
42
43
def print_grid():
44
do_twice(print_row)
45
print_beams()
46
47
print_grid()
48
49
50
# here is a less-straightforward solution to the
51
# four-by-four grid
52
53
def one_four_one(f, g, h):
54
f()
55
do_four(g)
56
h()
57
58
def print_plus():
59
print('+', end=' ')
60
61
def print_dash():
62
print('-', end=' ')
63
64
def print_bar():
65
print('|', end=' ')
66
67
def print_space():
68
print(' ', end=' ')
69
70
def print_end():
71
print()
72
73
def nothing():
74
"do nothing"
75
76
def print1beam():
77
one_four_one(nothing, print_dash, print_plus)
78
79
def print1post():
80
one_four_one(nothing, print_space, print_bar)
81
82
def print4beams():
83
one_four_one(print_plus, print1beam, print_end)
84
85
def print4posts():
86
one_four_one(print_bar, print1post, print_end)
87
88
def print_row():
89
one_four_one(nothing, print4posts, print4beams)
90
91
def print_grid():
92
one_four_one(print4beams, print_row, nothing)
93
94
print_grid()
95
96
comment = """
97
After writing a draft of the 4x4 grid, I noticed that many of the
98
functions had the same structure: they would do something, do
99
something else four times, and then do something else once.
100
101
So I wrote one_four_one, which takes three functions as arguments; it
102
calls the first one once, then uses do_four to call the second one
103
four times, then calls the third.
104
105
Then I rewrote print1beam, print1post, print4beams, print4posts,
106
print_row and print_grid using one_four_one.
107
108
Programming is an exploratory process. Writing a draft of a program
109
often gives you insight into the problem, which might lead you to
110
rewrite the code to reflect the structure of the solution.
111
112
--- Allen
113
"""
114
115
print(comment)
116
117