# pairs.py # Walker M. White (wmw2), Lillian Lee (LJL2), Steve Marschner (srm2) # November 5, 1013 """Module to show off loop invariants in a function""" import sys def num_adj_pairs(s): """Returns: number of adjacent equals pairs in s And adjacent pair has the form s[k-1], s[k]. Example: num_adj_pairs('ebeee') is 2 Precondition: s is a string""" # Set x to # adjacent equal pairs in s[0..len(s)-1] x = 0 k = 1 # inv: x = # adjacent equal pairs in s[0..k-1] while k < len(s): # Process k print 'loop:', x, 'pairs in', s[0:k] if (s[k-1] == s[k]): x = x + 1 k = k + 1 # x = # adjacent equal pairs in s[0..len(s)-1] print 'post:', x, 'pairs in', s return x if __name__ == '__main__': assert len(sys.argv) == 2 s = sys.argv[1] # get string from command line x = num_adj_pairs(s) print 'The number of matching adjacent pairs in ' + `s` + ' is '+str(x)