# Fernando Guevara Vasquez, 2014
import re,operator,string
def count_patterns(patterns):
    """
    Count all repetitions of the same string in the list of strings *patterns*. The result is printed in alphabetical order
    """
    counts = {}
    for pattern in patterns:
        i=counts.setdefault(pattern.lower(),0)
        counts[pattern.lower()]=i+1
    counts_sorted = sorted(counts.iteritems(), key=operator.itemgetter(1),reverse=True)
    for i in counts_sorted: 
        print " %s: %d " % i

def count_letters(text):
    """
    Count number of different letters in *text* and print frequency table
    (case insensitive)
    """
    letters = re.findall(r"\w",text,re.IGNORECASE) # find all letter characters
    count_patterns(letters)

def count_word2(text):
    """
    Count number of different two letter words in *text* and print frequency table
    this assumes the encoded message has preserved punctuation and spaces
    (case insensitive)
    """
    word2=re.findall(r"\b\w\w\b",text,re.IGNORECASE) # find all 2 letter words
    count_patterns(word2)

def count_word3(text):
    """
    Count number of different three letter words in *text* and print frequency table
    this assumes the encoded message has preserved punctuation and spaces
    (case insensitive)
    """
    word3=re.findall(r"\b\w\w\w\b",text,re.IGNORECASE) # find all 3 letter words
    count_patterns(word3)

def translit(text,code):
    """
    Substitution cypher

    Inputs:
     *text* - to cypher (or uncypher)
            assumed UPPERCASE
    
     *code* - the substitition for the alphabet. All substituted letters
            are assumed lowercase.
    
    Outputs:
        a string with the substituted text

    example::

     print translit("HELLO WORLD","zyxwvutsrqponmlkjihgfedcba")
     svool dliow

    """
    for i in range(ord('A'),ord('Z')+1):
        text=re.sub(chr(i),code[i-ord('A')],text)
    return text
