""" datatools.py c odenthal 2005/05/30 This module contains some data manipulation functions. """ from __future__ import division def sortByKey(dct,ascending=True): """ Returns a list containing the (key,value) pairs of the dictionary 'dct' sorted by key. """ lst = dct.items() lst.sort() if not ascending: lst.reverse() return lst def sortByValue(dct,ascending=False): """ Returns a list containing the (key,value) pairs of the dictionary 'dct' sorted by value. """ lst = [(v,k) for k,v in dct.items()] lst.sort() if not ascending: lst.reverse() return [(k,v) for v,k in lst] def dict2array(dct,rowkeys,colkeys): """ This takes a dictionary 'dct' with keys of the form 'cd' where 'c' and 'd' are letters. The output is a string that displays the entries of 'dct' as an array with the rows ordered by 'rowkeys' and the columns ordered by 'colkeys'. The assumption is that the values in 'dct' are less than 5. These values are multiplied by 200 and rounded (truncated?) to integer values that will be between 0 and 99. """ # Form the array. lst = [[dct.get(r+c,0) for c in colkeys] for r in rowkeys] # Scale the entries and truncate to integers. scale = lambda x : int(200*x) lst = [map(scale,row) for row in lst] # Convert the entries to strings. lst = [map(str,row) for row in lst] # Right-justify the entries. format = lambda s: s.rjust(3) lst = [map(format,row) for row in lst] # Insert the row labels. lst = [[rowkeys[i].center(3)] + row for (i,row) in enumerate(lst)] # Join each row into a line. lst = ["".join(row) for row in lst] # Join the lines into a single string. strng = "\n".join(lst) # Now make the header. hdr = "".join([c.rjust(3) for c in colkeys]) hdr = "\n" + " "*3 + hdr + "\n" + "-"*81 + "\n" return hdr + strng def transpose(lstLst): """ Computes the 'transpose' of an array - a list of lists. """ return apply(zip,lstLst) def gcd(a,b): try: return gcd(b,a%b) except: return abs(a)