-1

I'm writing a function that can return whether a hand of cards has a royal flush or not. I've tried various different methods but none seem to work; some methods return always false and some return always true.

Below is a method that always returns true

davesCards = ['10C','10S','QC','KC','AC','10S','4C'] #this should return false

def royalFlushCheck(playerCards):
    if '10S' and 'JS' and 'QS' and 'KS' and 'AS' in playerCards:
        return True
    if '10H' and 'JH' and 'QH' and 'KH' and 'AH' in playerCards:
        return True
    if '10C' and 'JC' and 'QC' and 'KC' and 'AC' in playerCards:
        return True
    if '10D' and 'JD' and 'QD' and 'KD' and 'AD' in playerCards:
        return True
    return False

royalFlushCheck(davesCards)

This returns True when it should be false as there is no Jack of Clubs card. I assumed the and operator would make it so the function only returned True if all the cards were in the array. I'm relatively new to these things so would appreciate a beginer's explanation

(edit) I have been marked a duplicate but I had already previously seen the question referenced and did not get the answer I wanted from it which is why I posted the question with my specific situation.

callumbous
  • 173
  • 1
  • 1
  • 12
  • A couple of `elif`s would be better than multiple `if`s to start. – Onilol Oct 20 '15 at 18:36
  • 2
    The `and` is evaluated `True` for pair of strings you are using, it does not check its presence in the list. The deciding comparison is only the last one. So `if '10C' and 'JC' and 'QC' and 'KC' and 'AC' in playerCards:` evaluates to `True` as `AC` is in the `playerCards`. So this is not correct syntax. Should be easy to fix. –  Oct 20 '15 at 18:46

2 Answers2

2

Your code just checks if 'AS' or 'AH' or 'AC', 'AD' is in the list or not. More elegant way would be to use subset.

if set(royalFlush).issubset(set(davesCards)):
    return True

where royalFlush = ['AS','JS','QS','KS','10S']

Or as suggested in comments:

return set(royalFlush).issubset(davesCards)
blackmamba
  • 1,952
  • 11
  • 34
  • 59
0

You can make this shorter by separating out rank and suit

def royalFlushCheck(playerCards):
    suits = [card[-1] for card in playerCards]
    ranks = [card[:-1] for card in playerCards]
    allRanks = all([rank in ranks for rank in ['10', 'J', 'Q', 'K', 'A']])
    sameSuit = len(set(suits)) == 1
    return allRanks and sameSuit
C.B.
  • 8,096
  • 5
  • 20
  • 34