r/programminghelp • u/[deleted] • 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 res1
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 resFor more on destructuring, look here:
https://blog.tecladocode.com/destructuring-in-python/
1
u/amoliski Jul 25 '20
Python is a duck-typed language, which means any function will accept any type of object as an argument, as opposed to other languages where a function will only accept a specific object.
This can be really handy when using python as a scripting language, because it make it really flexible.
Say you have a function that takes a
file_objectand callsfile_object.write(data)on it. You can give it any object with a 'write()' function and it will just work. You don't need to rewrite the original function if you instead want to have it just print to the console or save it to some internet cloud service- just give it an object with a.writefunction and it will work.But that also can lead to problems. Say you are given a function called
highFivethat accepts an argument 'items' - you have no idea what the 'items' is supposed to be. You'd have to dig into the object to figure out how it works. To solve this, python 3.5 added type hints. You can read about them here: https://docs.python.org/3/library/typing.html - Type hints let you (and your IDE) know what a function is expecting to receive as an argument and what it should expect to get back from the function.---
So, now let's look at:
def highFive(self, items: List[List[int]]) -> List[List[int]]:What that syntax is saying is "I am expecting to be given a list of lists of integers" (your input example) and I will return a List of Lists of Integers (the output example). These things can get a little complicated, so to be super clear, a list of integers would look like
[1,2,3], and a list of lists of integers would look like[[1,2,3], [6,5,4], [7,8,9]]If you are using an IDE that supports the feature, it will give you a warning if you try to pass the function a string, instead of the List of Lists of ints it's expecting.
---
By the way, Your code is missing "
from typing import List" without it (or if you're under python 3.5), your code won't work and will complain that it doesn't know what a List is.