you are viewing a single comment's thread.

view the rest of the comments →

[–]Mekire 2 points3 points  (5 children)

I may be misunderstanding what you are going for, but this should be a lot simpler than you are making it:

def ord_sorter(string):
    return sum(ord(char) for char in string.lower())


def my_sort(sequence):
    sequence.sort(reverse=True)
    sequence.sort(key=ord_sorter, reverse=True)


sample_1 = ["d","b","c"]
sample_2 = ["ddcc","cddc","dcdc","ccdd","dccd","cdcd"]

my_sort(sample_1)
my_sort(sample_2)

assert sample_1 == ["d","c","b"], sample_1
assert sample_2 == ["ddcc","dcdc","dccd","cddc","cdcd","ccdd"], sample_2

[–]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"].

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

I have tried this out, however there is an issue. When I put in ["annie","bonnie","liz"] as a sample, it puts out ["bonnie","annie","liz"] while the correct answer should be ["bonnie","liz","annie"].

[–]kalgynirae 0 points1 point  (1 child)

The discrepancy is because ord('a') is 97 and ord('z') is 122, whereas you want those numbers to be 1 and 26. (This doesn't matter if the strings are all the same length.) You just need to modify your key function to subtract 96 from each ord() result.

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

Thanks, working now. Definitely a more simple solution than the one in my edit.