ABSP, Ch 6, Practice Project

My solution to the Practice Project in Chapter 6 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 10/08/2017
# write a table printer function that takes a list of lists
# (of the same length) of strings and displays it in a table with each column right-justified.
# NOTE: if you want to print the table with the amount of right-justification
#       equal to the longest string contained in the table use the two commented out lines belowe
#       and substitute print(tableData[j][i].rjust(colWidths[j]), end = ' ')
#       with print(tableData[j][i].rjust(maxColWidth), end = ' ')

def printTable(tableData):
    colWidths = [0] * len(tableData)
    for aList in range(len(tableData)):
        for item in tableData[aList]:
            if len(item) > colWidths[aList]:
                colWidths[aList] = len(item)

    numItems = len(tableData[0]) # we assume all lists inside tableData of equal length
#   colWidths.sort(reverse = True)
#   maxColWidth = colWidths[0]
    for i in range(numItems):
        for j in range(len(tableData)):
            print(tableData[j][i].rjust(colWidths[j]), end = ' ')

aTableData = [['apples', 'oranges', 'cherries', 'banana'],
              ['Alice', 'Bob', 'Carol', 'David'],
              ['dogs', 'cats', 'moose', 'goose']]

Comments about the code are welcome.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s