# Given a string 'str', this counts all substrings with length 2 and # print them in decreasing order with their frequecies def countsubstrings(str): ''' count all substrings with length 2 and return count = [(n1, str1), (n2, str2), ...] the order is not considered ''' count = [] for i in range(len(str)): substr = str[i:i+2] # substring with length 2 if len(substr) < 2: continue # substr must have at least two length # check if 'substr' is in count for i in range(len(count)): (n, s) = count[i] if s == substr: count[i] = (n+1, s) break else: # this part is executed only if no 'break' in the above for loop count.append((1, substr)) return(count) if __name__ == '__main__': import sys str = sys.argv[1] # print str # for debug count = countsubstrings(str) # print count # for debug count.sort() count.reverse() # print all substrings in decreasing order with their frequencies for (n, s) in count: print s, " occurs ", n, " times"