Pages

CodeEval Simple or trump

Given in input a representation of two cards and the current trump, return the highest one, or both if they have the same value.
This is the CodeEval problem #235 and here I am giving a Python 3 solution.

Cards are represented by their value, a number or the first letter in case of Jack, Queen, King, Ace, and the suit (Clubs, Diamonds, Hearts, Spades) initial. I have converted the sample provided in python test cases:
def test_provided_1(self):
    self.assertEqual('2H', solution('AD 2H | H'))

def test_provided_2(self):
    self.assertEqual('KD KH', solution('KD KH | C'))

def test_provided_3(self):
    self.assertEqual('JH', solution('JH 10S | C'))
The problem is so easy that I went for the fastest solution jumped to my mind, without caring much of anything possibly more refined.
Splitting the input line I get the facial description of the card, for instance KD for the King of Diamonds, and the current trump, as C for Club.

Then I wrote a puny, unsophisticated function that takes in input as a two-element list the cards, and the trump. I trivially converted the values in integers and then used the trump as a x10 multiplier. The idea is that even the lowest value card, a deuce (2), when is a trump has a value higher than the highest non-trump card.
def values(cards, trump):
    result = [0, 0]
    for i in [0, 1]:
        suit = cards[i][-1] # 1
        value = cards[i][:-1] # 2
        if value == 'J':
            result[i] = 11
        elif value == 'Q':
            result[i] = 12
        elif value == 'K':
            result[i] = 13
        elif value == 'A':
            result[i] = 14
        else:
            result[i] = int(value)

        if suit == trump:
            result[i] *= 10
    return result
1. Suit is the last character in the card description.
2. Value is the card description stripped of its last character.

Finally, it is just a matter of returning the face description of the highest card, or both, if they have the same value.

CodeEval accepted this solution, and I pushed test cases and python script.

No comments:

Post a Comment