from random import randrange

def big_list(n):
    """Create a list of n 'random' values in the range [-n/2,n/2]"""
    return [ randrange(-n//2, n//2) for i in range(n) ]


def unique(a):
    """Return a list containing each value in a exactly once"""
    b = []
    added = set()
    for x in a:
        if x not in added: 
            b.append(x)
            added.add(x)
    return b

def once_only(a):
    """Return a list containing only the unique values in a"""
    frequencies = freq(a)
    return [x for x in a if frequencies[x] == 1]

def negated(a):
    """Return a list containing only the values x in a where -x is also in a"""
    s = set(a)
    return [x for x in a if -x in s]

def freq(a):
    """Return a dictionary of element/frequency pairs in a"""
    frequencies = {}
    for x in a:
        if x in frequencies:
            frequencies[x] = frequencies[x] + 1
        else:
            frequencies[x] = 1
    return frequencies

def at_least(a, n):
    """Select the elements in a that occur at least n times"""
    frequencies = freq(a)
    return [x for x in a if frequencies[x] >= n]

import string 

def common_words(f, n):
    """Print out the n most common words in the file f"""
    words = open(f).read().lower().split()
    words = [ string.translate(w, None, string.punctuation) for w in words ]
    words = [ w for w in words if w != '']
    frequencies = freq(words)
    freqwords = [ (frequencies[w], w) for w in frequencies ]
    freqwords.sort()
    for pair in freqwords[len(freqwords)-1:-n:-1]:
        print "%s (%d)" % (pair[1], pair[0])
    

