you could use sort
according to the length of the list, and use a dictionary so the last written key "wins".
Then convert back to tuple
or list
or ... leave as dict
:
val = [(200, []), (300, [500, 200]), (400, [100, 200, 300]), (400, [])]
def largest_val_arrangement(val):
return tuple({k:v for k,v in sorted(val, key = lambda t : len(t[1]))}.items())
largest_val_arrangement(val)
result:
((200, []), (400, [100, 200, 300]), (300, [500, 200]))
This method, like the sort
it uses, has O(log(n)*n)
complexity, (dict
has O(1)
average complexity).
But one-liners aren't always the most efficient solutions. Here using sort
is unnecessary, when a good old loop with a marker dict works in O(n)
:
def largest_val_arrangement(val):
d = dict()
for k,v in val:
if k not in d or len(d[k]) < len(v):
d[k] = v
return tuple(d.items())