Simplify Code
Terry Reedy
tjreedy at udel.edu
Tue Jul 15 16:16:41 EDT 2008
Victor Subervi wrote:
> I set the following variables:
> # Headers are kept in order to determine nesting of chapters
> # They are labeled according to font size
> h36 = ''
> h26 = ''
> h22 = ''
> h18 = ''
> h14 = ''
> h12 = ''
> header_sizes = [36, 26, 22, 18, 14, 12]
> # Size is the font size of the header
> size = 0
>
> I write code that grabs the size var.
> Then I have the following very laborious spaghetti code:
>
> if size == 36:
> h36 = line
> h26 = ''
> h22 = ''
> h18 = ''
> h14 = ''
> h12 = ''
> elif size == 26:
> h26 = line
> h22 = ''
> h18 = ''
> h14 = ''
> h12 = ''
> elif size == 22:
> h22 = line
> h18 = ''
> h14 = ''
> h12 = ''
> elif size == 18:
> h18 = line
> h14 = ''
> h12 = ''
> elif size == 14:
> h14 = line
> h12 = ''
> elif size == 12:
> h12 = line
> else:
> # THROW ERROR!
Multiple elifs indicate a possible use for dicts. Untested possibility
header_sizes = [36, 26, 22, 18, 14, 12]
header_num = len(header_sizes)
header_blank = ['']*header_num # makes resetting headers much easier!
header_dexes = dict(zip(header_sizes, range(header_num)))
hearders = header_blank[0:] #initialize
# You can now change header_sizes length and contents
# and others will be built to match
..
def adjust_headers(size, line):
dex = header_dexes[size]
headers[dex] = line
headers[dex+1:] = header_blank[dex+1:]
Terry Jan Reedy
More information about the Python-list
mailing list