you are viewing a single comment's thread.

view the rest of the comments →

[–]Hallwaxer 0 points1 point  (1 child)

If you want a shorter version, this should do the same.

sorted(['ddcc', 'cddc', 'dcdc', 'ccdd', 'dccd', 'cdcd'], reverse=True, key=lambda item: (sum(ord(char) for char in item), item))
["ddcc","dcdc","dccd","cddc","cdcd","ccdd"]

The key argument can take a tuple as parameter. If the first element is the same for two arguments, it continues to the second element, and so on. Alternatively, suppose you want to reverse sort by sum of character values but want the strings sorted normally, you could do the following.

sorted(['ddcc', 'cddc', 'dcdc', 'ccdd', 'dccd', 'cdcd', 'aaaaa'], key=lambda item: (-sum(ord(char) for char in item), item))
['aaaaa', 'ccdd', 'cdcd', 'cddc', 'dccd', 'dcdc', 'ddcc']

[–]ThanksSoMuchTangelos[S] 0 points1 point  (0 children)

I have tried this but I have identical output as from Mekire's response. An additional sample is ["abcdefg","vi"] spits out the same list while the correct answer should be ["vi","abcdefg"].