Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Improve this by making the algorithm less complex

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For this, the same output is:

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

How can I improve the efficiency of this algorithm?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading