Search code examples
pythonsortingplaying-cards

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:

  • A
  • K
  • 4
  • 7
  • [everything else]

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

  • K
  • 7
  • 3
  • 2 or:
  • K
  • 7
  • 2
  • 3

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?


Solution

  • 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