Write a function named sort_deck()
which inputs a list containing valid integers (2 to
10) and valid strings ('Jack', 'Queen', 'King' and 'Ace') with exact spellings. This function
should return the same list after sorting
(2,3,4,5,6,7,8,9,'Jack','Queen','King','Ace')
Example 1: sort_deck(['Queen',2,'Jack',9])
Out: [2, 9, 'Jack', 'Queen']
CodePudding user response:
You could use a dictionary and the sorted
builtin:
You can use dict.get
, thus you only need to encode the faces
def sort_deck(deck):
faces = {'Jack': 11, 'Queen': 12, 'King': 13, 'Ace': 14}
return sorted(deck, key=lambda x: faces.get(x, x))
Just for the sake of generalization here is a way to generate the faces dictionary for an arbitrarily long list of faces:
from itertools import count
faces = dict(zip(['Jack', 'Queen', 'King', 'Ace'], count(11)))
CodePudding user response:
Assuming that cards have to be unique in any given shuffled deck, you can implement this using a presorted deck without using sorting at all:
>>> sorted_deck = [2, 3, 4, 5, 6, 7, 8, 9, 'Jack', 'Queen', 'King', 'Ace']
>>> deck = ['Queen', 2, 'Jack', 9]
>>> [card for card in sorted_deck if card in deck]
[2, 9, 'Jack', 'Queen']
You can further optimise this by converting deck to a set, i.e. deck = set(deck)
.