Advertisement
agf

Range Updater

agf
Aug 4th, 2011
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. def update(mylist, row, col, cmprow, cmpcol):
  2.     lo, hi = mylist[row][col]
  3.     low, high = mylist[cmprow][cmpcol]
  4.  
  5.     # always replace the current value if it's (-1, -1)
  6.     if (lo, hi) == (-1, -1):
  7.         mylist[row][col] = low, high
  8.         print "replacing empty", row, col, "with", cmprow, cmpcol
  9.         return
  10.  
  11.     # never replace the current value if the ranges don't overlap
  12.     # or the other range is (-1, -1)
  13.     if (low, high) == (-1, -1) or lo >= high or hi <= low:
  14.         print row, col, "doesn't overlap", cmprow, cmpcol
  15.         return
  16.  
  17.     # set the low to the highest low and the high to the lowest high
  18.     print "updating", row, col, "with", cmprow, cmpcol
  19.     mylist[row][col] = max((lo, low)), min((hi, high))
  20.  
  21.  
  22.  
  23. def update_ranges(oldlist):
  24.     # make a copy of the list as we're going to modify it
  25.     mylist = oldlist[:]
  26.     # we don't need the row titles, they just complicate things
  27.     rowtitles, mylist = zip(*mylist)
  28.     rows = len(mylist)
  29.     columns = range(len(mylist[0]))
  30.  
  31.     # for each row except the last
  32.     for i in xrange(rows - 1):
  33.         # update it by going down all the rows below it
  34.         for k in xrange(i+1, rows):
  35.             # for both columns
  36.             for j in columns:
  37.                 update(mylist, i, j, k, j)
  38.  
  39.     # put the row titles back in
  40.     mylist = zip(rowtitles, mylist)
  41.     return mylist
  42.  
  43.  
  44.  
  45. def test():
  46.     oldlist = [ ('a', [ (-1, -1), (0.2, 0.4) ] ),
  47.                ('b', [ (0.3, 1.0), (-1, -1) ] ),
  48.                ('c', [ (-1, -1), (-1, -1) ] ),
  49.                ('d', [ (0.15, 0.35), (0.05, 0.15) ] ) ]
  50.     print "Original List"
  51.     print '\n'.join(str(l) for l in oldlist)
  52.     newlist = update_ranges(oldlist)
  53.     print "New List"
  54.     print '\n'.join(str(l) for l in newlist)
  55.  
  56. if __name__ == '__main__':
  57.     test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement