Zachary Berkowitz
Zachary Berkowitz

Reputation: 17

Python3 - Sort array into specific order

I'm writing a card game (Kalashnikov) in Python 3 and I want to sort the player's hand. Is it possible to use a sort of dictionary to sort the hands so that the important cards are in the correct order? I have no idea what method would be used.

The object of the game is to get A, K, 4, and 7 in the 4-card hand, so I need to line up the cards in the hand in this order:

If the original hand is 3, K, 7, 2, for instance, after sorting it would look like:

My current code (simplified to remove unnecessary stuff) is:

deck = shuffle()
print("Dealing", end="", flush=True)
    for i in range(4):
        print(".", end="")
        if player == 1:
            hand.append(deck.pop())
            oppHand.append(deck.pop())
        else:
            oppHand.append(deck.pop())
            hand.append(deck.pop())
        sleep(1.25)
    hand = sortHand(hand)
    oppHand = sortHand(oppHand)
    print(" [DONE]")

What should the function sortHand(hand) be?

Upvotes: 1

Views: 228

Answers (3)

David Kaftan
David Kaftan

Reputation: 2174

You can actually take advantage of the standard lib sorted function with the optional key variable:

def priority(element):
    if element == 'A':
        return -4
    if element == 'K':
        return -3
    if element == '4':
        return -2
    if element == '7':
        return -1
    return ord( element )

print(sorted(['1','4','K','7'], key=priority))

Upvotes: 1

superb rain
superb rain

Reputation: 5531

A short one: hand.sort(key='74KA'.find, reverse=True)

Note that find returns -1 if the value isn't found, so it maps the characters A, K, 4, 7 to (indices) 3, 2, 1, 0 and all other characters to -1. Which is the reverse of the desired order, hence the reverse=True to turn it into the desired order.

Upvotes: 1

Masklinn
Masklinn

Reputation: 42492

Is it possible to use a sort of dictionary to sort the hands so that the important cards are in the correct order? I have no idea what method would be used.

Python's sorted built-in function (as well as the list.sort method) have a key parameter which is what you need here: key is a function which transforms a value into a "rank" used for sorting, e.g. if you return 0 for "A" and 1 for "K", then "A" will be sorted before "K".

You could just define a dict of ranks, then use that as key:

import collections

ranks = collections.defaultdict(lambda: 5, {
    'A': 0,
    'K': 1,
    '4': 3,
    '7': 4,
})
hand = list('3K72')
print('before', ', '.join(hand))
# => before 3, K, 7, 2
hand.sort(key=lambda card: ranks[card])
print(' after', ', '.join(hand))
# =>  after K, 7, 3, 2

Upvotes: 2

Related Questions