r/programminghelp • • Jul 25 '20

Python Solution breakdown help - High Five problem (Python)

This is the High Five problem (Leetcode). I found the working solution pasted below (Python) and I don't understand it. I have a working knowledge of Python, but I'm thrown off by the different data structures. I made substitutions for the loops but the results did not convey anything of substance to me. I'm especially confused by items: List[List[int]]) -> List[List[int]

Can anyone break down the solution for me?

Problem:

Given a list of scores of different students, return the average score of each student's top five scores in the order of each student's id.
Each entry items[i]has items[i][0]the student's id, and items[i][1]the student's score.  The average score is calculated using integer division.
Example 1:
Input: [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
Output: [[1,87],[2,88]]
Explanation: The average of the student with id = 1 is 87. The average of the student with id = 2 is 88.6. But with integer division their average converts to 88.
Note:
1 <= items.length <= 1000
items[i].length == 2
The IDs of the students is between 1 to 1000
The score of the students is between 1 to 100
For each student, there are at least 5 scores

Solution:

class Solution:
    def highFive(self, items: List[List[int]]) -> List[List[int]]:
        items.sort(reverse=True)
        
        res = []
        curr = []
        idx = items[0][0]
        
        for i, val in items:
            if i == idx:
                if len(curr) < 5:
                    curr.append(val)
            else:
                res.append([idx, sum(curr) // len(curr)])
                curr = [val]
                idx = i
        
        res.append([idx, sum(curr) // len(curr)])
        
        res = res[::-1]
        
        return res
4 Upvotes

2 comments sorted by

View all comments

1

u/amoliski Jul 25 '20

As for the function itself:

class Solution:
    def highFive(self, items: List[List[int]]) -> List[List[int]]:
        
        # Takes the input and sorts it so all of a students'
        # scores are grouped together
        # Ex:
        # In : [[1,100],  [2, 60], [1,80], [1,90], [2,60]]
        # Out: [[2,80], [2,60], [1,100], [1, 90], [1,80]]
        items.sort(reverse=True)
        
        # Holds the result
        res = []

        # Holds the data for the student currently being processed
        curr = []

        # Gets the id of the first item of the first item of the input
        # Ex. items = [[2,80], [2,60], [1,100], [1, 90], [1,80]]  
        # items[0] = [2,80]
        # items[0][0] = 2
        idx = items[0][0]

        # Create a loop that goes over the items array
        # Because each item in the items array is itself an array, 
        # we can 'destructure' it so that 'i' is the first element
        # and val is the second. (see below for more on destructuring)
        # Ex. items = [[2,80], [2,60], [1,100], [1, 90], [1,80]]
        # loop 1: i = 2, val = 80
        # loop 2: i = 2, val = 60
        # loop 3: i = 1, val = 100
        # etc...
 
        for i, val in items:
            # If the currently processing id is equal to the stored id
            # we append the score to the curr list. Otherwise, drop into 
            # the else block and start processing the next student
            if i == idx:
                if len(curr) < 5:
                    curr.append(val)
            # If we are here, it means the current student id has changed
            # Calculate the average for the previous student and store it
            else:
                res.append([idx, sum(curr) // len(curr)])
                curr = [val]
                idx = i
        # Once we get here, we have all of the students processed 
        # except the last one. store it. 
        res.append([idx, sum(curr) // len(curr)])
        
        # reverse the list
        res = res[::-1]
        
        # return the result
        return res

For more on destructuring, look here:
https://blog.tecladocode.com/destructuring-in-python/