ich las heute morgen auf reddit eine nette Aufgabe und dachte, dass ich das mal selber probieren muss:
Meine Lösung so weit:Rank Vectors
Given an array (or list) of scores, return the array of ranks for each value in the array. The largest value has rank 1, the second largest value has rank 2, and so on. Ties should be handled by assigning the same rank to all tied values. For example:
ranks([9,3,6,10]) = [2,4,3,1] and ranks([3,3,3,3,3,5,1]) = [2,2,2,2,2,1,7]
because there is one 1st place value, a five-way tie for 2nd place, and one in 7th place.
Code: Alles auswählen
def ranks(values):
counts = Counter(values)
rank_sum = 1
rank_values = {}
for value in sorted(counts.keys(), reverse=True):
rank_values[value] = rank_sum
rank_sum += counts[value]
return [rank_values[value] for value in values]
assert(ranks([9,3,6,10]) == [2,4,3,1])
assert(ranks([3,3,3,3,3,5,1]) == [2,2,2,2,2,1,7])Man könnte das ganze natürlich als Iterator-Funktion schreiben, aber laut Aufgabe soll ja ein "Array" (was offenbar eine Liste sein soll) zurück gegeben werden.
Ich habe tatsächlich noch nicht auf reddit gespickt, was da so an Lösungen angeboten wird
