We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

defluckBalance(k,contests):# sort from greatest luck to least luckcontests.sort(reverse=True)luck=0forcontestincontests:ifcontest[1]==0:luck+=contest[0]elifk>0:luck+=contest[0]k-=1else:luck-=contest[0]returnluck

It took a lot of whiteboarding to clearly put out what I wanted. Sorted the nested list by the first value, number of points, and from there chose which points I wanted to add and which points I needed to subtract. Thanks to @hubrando for the code review, took out an unnecessary variable and utilized an existing one.

same idea, but your solution is much clearer and more concise

defluck_balance(k,contests):# group important and unimportant contestssorted_contests=sorted(contests,key=itemgetter(1))groups=tuple(list(g)fork,ginit.groupby(sorted_contests,key=itemgetter(1)))iflen(groups)>1:unimportant,important=groupselifgroups[0][0][1]==0:unimportant,important=groups[0],[]else:unimportant,important=[],groups[0]# calculate how many matches we need to throwthrows=len(important)-kifthrows<1:returnsum(luckforluck,_inimportant+unimportant)# start by sorting important contests to throw the smallest in terms of lucksorted_important=sorted(important)# group wins and losseslosses,wins=sorted_important[:throws],sorted_important[throws:]# do mathtotal=sum(luckforluck,_inwins+unimportant)net=total-sum(luckforluck,_inlosses)returnnet

Good clean solution, very similar to what I did, but I didn't introduce a new important variable and just directly decremented k instead and checked if k was greater than 0 instead of important < k.

## Luck Balance

You are viewing a single comment's thread. Return to all comments →

My

updatedPython3 solution:It took a lot of whiteboarding to clearly put out what I wanted. Sorted the nested list by the first value, number of points, and from there chose which points I wanted to add and which points I needed to subtract. Thanks to @hubrando for the code review, took out an unnecessary variable and utilized an existing one.

same idea, but your solution is much clearer and more concise

Good clean solution, very similar to what I did, but I didn't introduce a new important variable and just directly decremented k instead and checked if k was greater than 0 instead of important < k.

A slightly more python way -

Very clean answer. sort() is very useful. For loop is efficient by looping every list in the nested list.