I have a list in which I am trying to find the count of the last element’s last character. I had it working, and then it stopped. I am not sure why. self.hand[-1][-1] returns 'h', which the count should return 5. However, I am not getting 5, I return 0.
poker_hand.py
class PokerHand:
def __init__(self, hand):
self.hand = hand
self.flush = False
def is_flush(self):
if self.hand.count(self.hand[-1][-1]) == 5:
self.flush = True
main.py
from poker_hand import PokerHand, test_hand_one, test_hand_two
test_hand_one = ['Jh', 'Qh', 'Kh', 'Ah', '10h']
if __name__ == '__main__':
hand_one = PokerHand(test_hand_one)
hand_one.is_flush()
print(hand_one.flush)
current output: False
>Solution :
For the hand in your example,
self.hand[-1][-1] is the last character in the string in the final position of the list, which is h.
So this line is evaluating self.hand.count('h'), i.e. you are asking "how many times does 'h' appear in self.hand?". It appears zero times (because Jh is not equal to h, Qh is not equal to h, etc.).
You need to ask "how many elements in self.hand have h in the final position?"
One way you could do this is with a list comprehension. The code will probably be clearer if you split into two lines.
last_card_suit = self.hand[-1][-1]
if len([card for card in self.hand if card[-1] == last_card_suit]) == 5:
...
Another way would be to get the suits of all the cards, then check that there is only one unique element using set.
suits = [card[-1] for card in self.hand]
if len(set(suits)) == 1:
...