Sunday, August 15, 2010

Pretty printing a vector in Python

Users of R gets a nicely aligned rectangular display when printing a vector to the console. Here is a Python function to pretty print a vector of floating point real numbers.

def maxdigits(n):
    #number of decimal digits in positive integer n.
    n = abs(n) # default behaviour for negative numbers.
    d = 0
    while n:
        n = n // 10
        d += 1
    return max(d,  1)

def vecprint(X, cols = 10, printwidth=10,  decimals = 7, withcount = True, 
             offset = 0):
    """
    Pretty prints a vector with cols elements per row.
    Format for each number is  printwidth wide with decimals.
    Arguments
        X                  input vector
        cols              number of columns in each to print
        printwidth    number of characters per element
        decimals      number of trailing fractional digits after decimal point.
        withcount     display starting index per row.
        offset            0 for Python, 1 for Fortran or R. 
    """
    L = len(X)
    d = maxdigits(L)
    startcount =0
    while L > 0:
        if withcount:
            print "[%*d]" % (d,  startcount+offset), 
        for j in range(min(cols,  L)):
            print "%*.*f"  % (printwidth,  decimals,  X[startcount+ j]), 
        print
        startcount  += cols
        L = L - cols

if name=="__main__":        
   import scipy.stats as stat
   X = stat.norm.rvs(0, 10, size= 101)

   vecprint (X,  cols = 10, printwidth = 10,  decimals = 6, withcount = True,  offset= 1)


When the above program runs, it prints out


python test.py
[  1] -12.274544  24.962005   0.898519   8.298623  -5.206765  11.369435   2.844898   5.382779   8.871070 -10.778256
[ 11]   8.993302   0.122253 -12.870449   6.865899  -0.013347  -6.294830   6.737924  -3.464933 -22.138001  -5.830818
[ 21]   4.333220   1.212900 -10.323043  -2.362759  -4.030961  -8.217033   5.081078  -1.496543  12.623560 -13.239969
[ 31]  19.963765 -27.012378   2.662621   8.417971 -11.408826 -11.900326  13.602873  -1.835010 -13.824051   1.494528
[ 41]  16.184007  -8.594634  12.703305  -3.304798   2.455711  -5.566551  -7.778173   5.475580  -4.503368  -5.652534
[ 51]  -9.810076 -13.494154  47.439976   5.627506  -1.501500 -17.052534   1.487389   8.717306   1.645366 -22.285412
[ 61]   8.923515 -14.373864  -4.206617 -13.933159   0.142266   8.084607 -16.791519   3.783785  18.676505  -6.416143
[ 71]  -1.453329  -6.619796  10.727761   1.809717   8.193551   9.959034  -3.531820 -10.767832   4.450496  -4.931875
[ 81]   1.994453   7.415965   6.156138   8.437512   3.415086   9.394266  27.906924 -16.393906 -10.795677   1.990537
[ 91] -16.822923   1.512371  10.182129  10.210412  -6.038684   7.556653   5.627985   8.988172  19.519813  -4.976217
[101]  11.222303

No comments:

Post a Comment