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.
    """
    tfidfs = []
    for file in files:
        score = 0
        for word in query:
            score += idfs[word] * files[file].count(word)
        tfidfs.append((file, score))
    tfidfs.sort(key=lambda x: x[1], reverse=True)
    return [j[0] for j in tfidfs[:n]]