Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List element not being counted?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading