""" A module to show off loop invariants in a function Authors: Walker M. White (wmw2), Lillian Lee (LJL2), Steve Marschner (srm2) Date: November 1, 2017 (Python 3 Version) """ import sys def num_adj_pairs(s): """ Returns: number of adjacent equals pairs in s An adjacent pair has the form s[k-1], s[k]. Example: num_adj_pairs('ebeee') is 2 Parameter s: the string to search 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 ' + repr(s) + ' is '+str(x))