Home > Enterprise >  In Python, trying to sort a poker hand by means of lambda and dictionary key
In Python, trying to sort a poker hand by means of lambda and dictionary key

Time:06-17

I have a hand contain certain cards, like this:

expectHandFormat = ['Ks','Qs','Ah','Ad','Ac','Jh','Qs','Ks','Ad']

I would like to sort them by their ranks then suits, as the suits in my game have different priority values.

However, sort() function seems to have only 1 key, while I need "priority" and "index" keys together.

I only managed to sort them with respect to Rank, like this:

hand = ['K','Q','A','A','A','J','Q','K','A']
rankPriority = {'A': 1, 'K': 2, 'Q': 3, 'J': 4}
suitPriority = {'s': 1, 'h': 2, 'c': 3, 'd': 4}
hand.sort(key=rankPriority.get)
# hand = ['A', 'A', 'A', 'A', 'K', 'K', 'Q', 'Q', 'J']

or sort them with expected format but no priority dictionary, like this:

hand = ['Ks','Qs','As','Ah','Ac','Jh','Qd','Kc','Ad']
hand.sort(key= lambda x: x[0])
# hand['As', 'Ah', 'Ac', 'Ad', 'Jh', 'Ks', 'Kc', 'Qs', 'Qd'], failed to follow A > K > Q...

Is there a way to sort the list at a certain index, at the same time sort with respect to user-defined priority? Thanks!

CodePudding user response:

You could encode each rank differently and then use the sum of both as an encoding.

hand = ['Ks','Qs','As','Ah','Ac','Jh','Qd','Kc','Ad']
rankPriority = {'A': 10, 'K': 20, 'Q': 30, 'J': 40}
suitPriority = {'s': 1, 'h': 2, 'c': 3, 'd': 4}
hand.sort(key=lambda x: rankPriority.get(x[0])   suitPriority.get(x[1]))

Or you could use the fact that tuples can be sorted in order of elements and use the solution proposed by Paul M. on the comment:

hand.sort(key=lambda card: (rankPriority[card[0]], suitPriority[card[1]]))

Here the sorting function will return a tuple, and python will sort on the first element then the second.

CodePudding user response:

I hope I'm understanding your problem correctly, it seems to me that the rank always has priority on the suit, therefore your problems boils down to ordering two digits numbers : see

hand.sort(key= lambda x: rankPriority[x[0]]*10   suitPriority[x[1]])
hand

output

['As', 'Ah', 'Ac', 'Ad', 'Ks', 'Kc', 'Qs', 'Qd', 'Jh']
  • Related