Home > Net >  Python: Improve this by making the algorithm less complex
Python: Improve this by making the algorithm less complex

Time:01-05

I have a working block of code, but it seems there should be a more efficient algorithm, presumably with less loops or using a library/module.

This example version of the code takes a list of strings, reverse sort by len(), then build a new list:

gs = ["catan", "ticket to ride", "azul"]

mg = {}
for i in range(len(gs)):
        mg[i] = len(gs[i])

popularity = {k: v for k, v in sorted(mg.items(), key=lambda v: v[1], reverse=True)}
tg = []
for game in popularity.keys():
        tg.append(gs[game])

The production code does not set mg[i] to len() and the elements in the list are not necessarily strings, but the algorithm works otherwise.

For this, the same output is:

['ticket to ride', 'catan', 'azul']

How can I improve the efficiency of this algorithm?

CodePudding user response:

gs = ["catan", "ticket to ride", "azul"]
tg = sorted(gs, key=len, reverse=True)

has the same effect for a list of strings.

If you want to sort the list in place for more space efficiency,

gs.sort(key=len, reverse=True)

This also works for a custom "criteria function":

def my_criteria_function(value):
    return len(value) * value.count(" ")  # super secret sauce

...sort(key=my_criteria_function) # (or sorted(..., key=my_criteria_function)
  • Related