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.
    """
    # Initialize scores to empty array
    scores = []

    # Loop through all documents
    for doc in files:
        score = 0

        # For each word in query, calculate term frequency, and idf,
        # and add total scores to the scores array
        for word in query:
            if word in files[doc]:
                score += files[doc].count(word) * idfs[word]
        scores.append((doc, score))

    # Sort scores in descending order with highest scores first
    scores = sorted(scores, key=lambda item: item[1], reverse=True)

    # Select 'n' top files to return
    top_files = [scores[i][0] for i in range(n)]

    return top_files