Python Rocks! and other rants 16.6.2004
Weblog of Kent S Johnson

2004-06-16

Python fashion statement

Did you know that you can buy a genuine python-skin bracelet? Here is one with a gold snake as well. According to the web site it is "sure to leave friends whispering!" I don't doubt that!

posted at 12:02:08    #    comment []    trackback []
 

Fun with difflib

I recently needed to show changes in the ordering of two lists in a way that makes sense to a person. Python's difflib makes this ridiculously easy. This little snippet does the trick:

import difflib

def showDiffs(old, new):
  
''' Show differences between two lists '''

  
# Get the diffs
  
diffs = difflib.SequenceMatcher(None, old, new).get_matching_blocks()

  
rowFormat = '%-10s  %s'
  
oldCurrent = newCurrent = 0

  
for oldIx, newIx, count in diffs:
      
# Catch up the output to the current diff position
      
while oldCurrent < oldIx:
          
print rowFormat % (old[oldCurrent], '')
          
oldCurrent += 1

      
while newCurrent < newIx:
          
print rowFormat % ('', new[newCurrent])
          
newCurrent += 1

      
# Write the common sequence
      
for i in range(count):
          
print rowFormat % (old[oldIx+i], new[newIx+i])

      
# Update current locations
      
oldCurrent = oldIx + count
      
newCurrent = newIx + count

Now showDiffs( [1,3,2,4], [1,2,3,4] ) prints out

1           1
            2
3           3
2           
4           4

Sweet!

This post references topics: python
posted at 11:40:48    #    comment []    trackback []
June 2004
MoTuWeThFrSaSu
  1 2 3 4 5 6
7 8 910111213
14151617181920
21222324252627
282930    
Apr
2004
 Jul
2004

Comments about life, the universe and Python, from the imagination of Kent S Johnson.

XML-Image Letterimage

BlogRoll

© 2004, Kent Johnson