I have a list of five-character strings, each string representing a hand of five playing cards. I want to sort each string so it's in ascending order by number, followed by the cards (T,J,Q,K,A). So “Q4JTK”, "9T43A" and “T523Q” will sort to “4TJQK”, "349TA" and “235TQ” respectively. I can sort a numeric five character string using:
def sort_string(s):
return ''.join(sorted(s))
print(sort_string("21437"))
But how to sort a string with numbers and letters? I would probably find a regular function easier to follow than a lambda function. Thanks.
I have a list of five-character strings, each string representing a hand of five playing cards. I want to sort each string so it's in ascending order by number, followed by the cards (T,J,Q,K,A). So “Q4JTK”, "9T43A" and “T523Q” will sort to “4TJQK”, "349TA" and “235TQ” respectively. I can sort a numeric five character string using:
def sort_string(s):
return ''.join(sorted(s))
print(sort_string("21437"))
But how to sort a string with numbers and letters? I would probably find a regular function easier to follow than a lambda function. Thanks.
Share Improve this question edited Mar 29 at 16:53 Derek O 19.7k4 gold badges29 silver badges49 bronze badges asked Mar 29 at 16:03 Peter4075Peter4075 991 silver badge5 bronze badges 3- why T come before K – sahasrara62 Commented Mar 29 at 16:21
- @sahasrara62 T = 10 – Andrew Morton Commented Mar 29 at 16:22
- oh my bad, its card game – sahasrara62 Commented Mar 29 at 16:23
2 Answers
Reset to default 6Sorting by index in the desired order:
def sort_string(s):
return ''.join(sorted(s, key='23456789TJQKA'.index))
print(sort_string('Q4JTK') == '4TJQK')
print(sort_string('9T43A') == '349TA')
print(sort_string('T523Q') == '235TQ')
Attempt This Online!
The issue that you're seeing it that Python's sorted() on strings with numbers and letters, sorts each character by its ASCII value (uppercase letters will come before numbers), which is not how cards would work when sorted. To fix it without a lambda expression so it's easier to follow would be doing something like mapping each character to a rank (i.e. 'A" : 1, '2': 2, etc...)
def card_rank(card):
rank_order = {
'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14
}
return rank_order[card]
def sort_string(s):
return ''.join(sorted(s, key=card_rank))
So here, sorted() accepts another optional parameter - the key function. And then sorted the string based off the assigned card's rank.
If it's difficult to understand how sorted() may work, I've attached the documentation here
https://www.programiz/python-programming/methods/built-in/sorted
Good Luck!