Skip to content

Instantly share code, notes, and snippets.

@xquery
Last active April 1, 2020 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xquery/e0ecef4e8aa313e0195140a3659986f7 to your computer and use it in GitHub Desktop.
Save xquery/e0ecef4e8aa313e0195140a3659986f7 to your computer and use it in GitHub Desktop.
Sort a list of the strings "a", "bcd", "ef", and "ghij" in descending order of length.
"""
How do you sort a list of the strings "a", "bcd", "ef", and "ghij" in descending order of length?
(https://twitter.com/paulg/status/1244921240227282944)
"""
def sort_desc_by_string_length(data):
''' sorts an array by string length and return in descending order '''
# use python 'sorted' builtin to sort by string length and return in reverse order
# (https://docs.python.org/3.8/library/functions.html?highlight=sorted#sorted)
return sorted(data, key=len, reverse=True)
data = [ "a", "bcd", "ef", "ghij"]
expected = ['ghij', 'bcd', 'ef', 'a']
result = sort_desc_by_string_length(data)
# should pass if correct
assert( expected==result)
print("success")
print(result)
@xquery
Copy link
Author

xquery commented Mar 31, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment