def top_files(query, files, idfs, n):
    """
    Given a `query` (a set of words), `files` (a dictionary mapping names of
    files to a list of their words), and `idfs` (a dictionary mapping words
    to their IDF values), return a list of the filenames of the the `n` top
    files that match the query, ranked according to tf-idf.
    """
    tf_idfs = []
    for filename, filewords in files.items():
        tf_idf = 0

        for word in query:
            if word not in idfs:
                continue
            idf  = idfs[word]
            tf = filewords.count(word)
            tf_idf += idf * tf
        t = (filename, tf_idf)
        tf_idfs.append(t)

    sorted_list = sorted(tf_idfs, key=lambda k: k[1])
    sorted_list.reverse()
    file_list = [item[0] for item in sorted_list]

    return file_list[:n]