1

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?

2
  • What is it supposed to do in the end? Commented Jan 4, 2023 at 17:08
  • Sort the list by the criteria largest number to smallest number. In this example the number is len(mg[i]). I'll add sample output Commented Jan 4, 2023 at 17:09

1 Answer 1

5
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)
Sign up to request clarification or add additional context in comments.

3 Comments

len is the same code, production doesn't use len()
It doesn't matter; substitute that function for len then.
Confirmed in production. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.